From 609194fae2332e6f2ccd7a4464bfa492ad661a6f Mon Sep 17 00:00:00 2001 From: Samuel Holland Date: Mon, 1 Jan 2018 02:06:37 -0600 Subject: Serviceless rewrite, part 1 Signed-off-by: Samuel Holland --- .../com/wireguard/android/util/AsyncWorker.java | 65 ++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 app/src/main/java/com/wireguard/android/util/AsyncWorker.java (limited to 'app/src/main/java/com/wireguard/android/util/AsyncWorker.java') diff --git a/app/src/main/java/com/wireguard/android/util/AsyncWorker.java b/app/src/main/java/com/wireguard/android/util/AsyncWorker.java new file mode 100644 index 00000000..5f9f0a83 --- /dev/null +++ b/app/src/main/java/com/wireguard/android/util/AsyncWorker.java @@ -0,0 +1,65 @@ +package com.wireguard.android.util; + +import android.os.Handler; + +import com.wireguard.android.Application.ApplicationHandler; +import com.wireguard.android.Application.ApplicationScope; + +import java.util.concurrent.Executor; + +import javax.inject.Inject; + +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. + */ + +@ApplicationScope +public class AsyncWorker { + private final Executor executor; + private final Handler handler; + + @Inject + public AsyncWorker(final Executor executor, @ApplicationHandler 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.3-18-gd494