aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/ui/src/main/java/com/wireguard/android/util/AsyncWorker.kt
blob: fd5eee2f5370c32386fecc6809e780730b27e082 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
 * Copyright © 2017-2020 WireGuard LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
package com.wireguard.android.util

import android.os.Handler
import java.util.concurrent.Executor
import java9.util.concurrent.CompletableFuture
import java9.util.concurrent.CompletionStage

/**
 * Helper class for running asynchronous tasks and ensuring they are completed on the main thread.
 */

class AsyncWorker(private val executor: Executor, private val handler: Handler) {

    fun runAsync(run: () -> Unit): CompletionStage<Void> {
        val future = CompletableFuture<Void>()
        executor.execute {
            try {
                run()
                handler.post { future.complete(null) }
            } catch (t: Throwable) {
                handler.post { future.completeExceptionally(t) }
            }
        }
        return future
    }

    fun <T> supplyAsync(get: () -> T?): CompletionStage<T> {
        val future = CompletableFuture<T>()
        executor.execute {
            try {
                val result = get()
                handler.post { future.complete(result) }
            } catch (t: Throwable) {
                handler.post { future.completeExceptionally(t) }
            }
        }
        return future
    }
}