Created
February 7, 2018 11:03
-
-
Save AlexMeuer/17cde445e25715f11a99245ffcb07f0b to your computer and use it in GitHub Desktop.
Very simple utility class for running stuff on an executor. Depends on Google Guava (written with 'com.google.guava:guava:23.3-android')
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo.bar.baz; | |
import android.support.annotation.CheckResult; | |
import android.support.annotation.NonNull; | |
import com.google.common.util.concurrent.ListenableFuture; | |
import com.google.common.util.concurrent.ListeningExecutorService; | |
import com.google.common.util.concurrent.MoreExecutors; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.Executors; | |
/** | |
* Utility class for running stuff in the background. | |
* Allows for fire-and-forget task running with optional listeners. | |
*/ | |
public class Background { | |
private static final ListeningExecutorService mBackgroundExecutor; | |
static { | |
mBackgroundExecutor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); | |
} | |
private Background() { /* Instantiation is not allowed. */ } | |
public static ListenableFuture run(@NonNull Runnable runnable) { | |
return mBackgroundExecutor.submit(runnable); | |
} | |
public static <V> ListenableFuture<V> run(@NonNull Callable<V> callable) { | |
return mBackgroundExecutor.submit(callable); | |
} | |
public static ListenableFuture run(@NonNull Runnable runnable, @NonNull Runnable listener) { | |
final ListenableFuture future = run(runnable); | |
future.addListener(listener, mBackgroundExecutor); | |
return future; | |
} | |
@CheckResult | |
public static <V> ListenableFuture<V> run(@NonNull Callable<V> callable, @NonNull Runnable listener) { | |
final ListenableFuture<V> future = run(callable); | |
future.addListener(listener, mBackgroundExecutor); | |
return future; | |
} | |
public static void addListener(@NonNull ListenableFuture future, @NonNull Runnable listener) { | |
future.addListener(listener, mBackgroundExecutor); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment