Skip to content

Instantly share code, notes, and snippets.

@wonsuc
Last active November 1, 2021 08:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wonsuc/353baa621ec896ffd2a3697c86f00c04 to your computer and use it in GitHub Desktop.
Save wonsuc/353baa621ec896ffd2a3697c86f00c04 to your computer and use it in GitHub Desktop.
A simple helper class to call tasks synchronously in Android's The Tasks API.
package app.pwdr.firebase.util;
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TasksUtil {
public static String TAG = "TasksUtil";
private static volatile TasksUtil sInstance;
private volatile ExecutorService mDefaultExecutor;
public static TasksUtil getInstance() {
if (sInstance == null) sInstance = new TasksUtil();
return sInstance;
}
public static void releaseInstance() {
if (sInstance != null) {
sInstance.release();
sInstance = null;
}
}
private void release() {
this.mDefaultExecutor.shutdown();
this.mDefaultExecutor = null;
}
private TasksUtil() {
this.mDefaultExecutor = getExecutor();
}
public ExecutorService getExecutor() {
if (mDefaultExecutor == null || mDefaultExecutor.isShutdown() || mDefaultExecutor.isTerminated()) {
// Create a new ThreadPoolExecutor with 2 threads for each processor on the
// device and a 60 second keep-alive time.
int numCores = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
numCores * 2,
numCores * 2,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>()
);
mDefaultExecutor = executor;
}
return mDefaultExecutor;
}
public static <TResult> Task<TResult> call(@NonNull Callable<TResult> callable) {
return Tasks.call(getInstance().getExecutor(), callable);
}
}
@wonsuc
Copy link
Author

wonsuc commented Mar 21, 2019

Here is a sample code.

import static com.google.android.gms.tasks.Tasks.await;

TasksUtil.call(() -> {
    await(FirebaseAuth.getInstance().signInAnonymously());

    // You can use multiple Tasks.await method here.
    User user = await(getUserTask());
    Profile profile =  await(getProfileTask());
    await(moreAwesomeTask());
    ...
    
    startMainActivity();
    return null;
}).addOnFailureListener(e -> {
    Log.w(TAG, "ERROR", e);
});

Feel free to comment and ask any questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment