]> git.ktnx.net Git - mobile-ledger.git/commitdiff
add an async runner class for general tasks
authorDamyan Ivanov <dam+mobileledger@ktnx.net>
Wed, 25 Aug 2021 20:25:31 +0000 (23:25 +0300)
committerDamyan Ivanov <dam+mobileledger@ktnx.net>
Wed, 25 Aug 2021 20:25:31 +0000 (23:25 +0300)
supposed to replace AsyncTask usage

app/src/main/java/net/ktnx/mobileledger/async/GeneralBackgroundTasks.java [new file with mode: 0644]

diff --git a/app/src/main/java/net/ktnx/mobileledger/async/GeneralBackgroundTasks.java b/app/src/main/java/net/ktnx/mobileledger/async/GeneralBackgroundTasks.java
new file mode 100644 (file)
index 0000000..1109219
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright © 2021 Damyan Ivanov.
+ * This file is part of MoLe.
+ * MoLe is free software: you can distribute it and/or modify it
+ * under the term of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your opinion), any later version.
+ *
+ * MoLe is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License terms for details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+package net.ktnx.mobileledger.async;
+
+import net.ktnx.mobileledger.utils.Misc;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+
+public class GeneralBackgroundTasks {
+    private static final Executor runner = Executors.newCachedThreadPool();
+    public static void run(@NotNull Runnable runnable) {
+        runner.execute(runnable);
+    }
+    public static void run(@NotNull Runnable runnable, @NotNull Runnable onSuccess) {
+        runner.execute(() -> {
+            runnable.run();
+            onSuccess.run();
+        });
+    }
+    public static void run(@NotNull Runnable runnable, @Nullable Runnable onSuccess,
+                           @Nullable ErrorCallback onError, @Nullable Runnable onDone) {
+        runner.execute(() -> {
+            try {
+                runnable.run();
+                if (onSuccess != null)
+                    Misc.onMainThread(onSuccess);
+            }
+            catch (Exception e) {
+                if (onError != null)
+                    Misc.onMainThread(() -> onError.error(e));
+                else
+                    throw e;
+            }
+            finally {
+                if (onDone != null)
+                    Misc.onMainThread(onDone);
+            }
+        });
+    }
+    public static abstract class ErrorCallback {
+        abstract void error(Exception e);
+    }
+}