]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/GeneralBackgroundTasks.java
add an async runner class for general tasks
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / GeneralBackgroundTasks.java
1 /*
2  * Copyright © 2021 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.async;
19
20 import net.ktnx.mobileledger.utils.Misc;
21
22 import org.jetbrains.annotations.NotNull;
23 import org.jetbrains.annotations.Nullable;
24
25 import java.util.concurrent.Executor;
26 import java.util.concurrent.Executors;
27
28 public class GeneralBackgroundTasks {
29     private static final Executor runner = Executors.newCachedThreadPool();
30     public static void run(@NotNull Runnable runnable) {
31         runner.execute(runnable);
32     }
33     public static void run(@NotNull Runnable runnable, @NotNull Runnable onSuccess) {
34         runner.execute(() -> {
35             runnable.run();
36             onSuccess.run();
37         });
38     }
39     public static void run(@NotNull Runnable runnable, @Nullable Runnable onSuccess,
40                            @Nullable ErrorCallback onError, @Nullable Runnable onDone) {
41         runner.execute(() -> {
42             try {
43                 runnable.run();
44                 if (onSuccess != null)
45                     Misc.onMainThread(onSuccess);
46             }
47             catch (Exception e) {
48                 if (onError != null)
49                     Misc.onMainThread(() -> onError.error(e));
50                 else
51                     throw e;
52             }
53             finally {
54                 if (onDone != null)
55                     Misc.onMainThread(onDone);
56             }
57         });
58     }
59     public static abstract class ErrorCallback {
60         abstract void error(Exception e);
61     }
62 }