aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/app/src/main/java/com/wireguard/android/util/AsyncWorker.java
blob: 201bd11852b3f43492ac17ebc116bc483cc5359f (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
 * Copyright © 2018 Samuel Holland <samuel@sholland.org>
 * Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. 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.
 */

public class AsyncWorker {
    private final Executor executor;
    private final Handler handler;

    public AsyncWorker(final Executor executor, final Handler handler) {
        this.executor = executor;
        this.handler = handler;
    }

    public CompletionStage<Void> runAsync(final AsyncRunnable<?> runnable) {
        final CompletableFuture<Void> future = new CompletableFuture<>();
        executor.execute(() -> {
            try {
                runnable.run();
                handler.post(() -> future.complete(null));
            } catch (final Throwable t) {
                handler.post(() -> future.completeExceptionally(t));
            }
        });
        return future;
    }

    public <T> CompletionStage<T> supplyAsync(final AsyncSupplier<T, ?> supplier) {
        final CompletableFuture<T> future = new CompletableFuture<>();
        executor.execute(() -> {
            try {
                final T result = supplier.get();
                handler.post(() -> future.complete(result));
            } catch (final Throwable t) {
                handler.post(() -> future.completeExceptionally(t));
            }
        });
        return future;
    }

    @FunctionalInterface
    public interface AsyncRunnable<E extends Throwable> {
        void run() throws E;
    }

    @FunctionalInterface
    public interface AsyncSupplier<T, E extends Throwable> {
        T get() throws E;
    }
}