From 0c161cc0c2bcd62ef10666d44107384cfc05b4b0 Mon Sep 17 00:00:00 2001 From: "Jason A. Donenfeld" Date: Mon, 9 Mar 2020 08:59:37 -0600 Subject: AsyncWorker: move back to original location Signed-off-by: Jason A. Donenfeld --- .../com/wireguard/android/util/AsyncWorker.java | 63 ++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 ui/src/main/java/com/wireguard/android/util/AsyncWorker.java (limited to 'ui/src/main/java/com/wireguard/android') diff --git a/ui/src/main/java/com/wireguard/android/util/AsyncWorker.java b/ui/src/main/java/com/wireguard/android/util/AsyncWorker.java new file mode 100644 index 00000000..1d041851 --- /dev/null +++ b/ui/src/main/java/com/wireguard/android/util/AsyncWorker.java @@ -0,0 +1,63 @@ +/* + * Copyright © 2017-2019 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. + */ + +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 runAsync(final AsyncRunnable runnable) { + final CompletableFuture 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 CompletionStage supplyAsync(final AsyncSupplier supplier) { + final CompletableFuture 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 { + void run() throws E; + } + + @FunctionalInterface + public interface AsyncSupplier { + T get() throws E; + } +} -- cgit v1.2.3