Starting with Google Play services version 9.0.0, you can use a Task
API and a
number of methods that return Task
or its subclasses. Task
is an API that
represents asynchronous method calls, similar to PendingResult
in previous
versions of Google Play services.
Handling task results
A common method that returns a Task
is FirebaseAuth.signInAnonymously()
.
It returns a Task<AuthResult>
which means the task will return
an AuthResult
object when it succeeds:
Task<AuthResult> task = FirebaseAuth.getInstance().signInAnonymously();
To be notified when the task succeeds, attach an OnSuccessListener
:
task.addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { // Task completed successfully // ... } });
To be notified when the task fails, attach an OnFailureListener
:
task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Task failed with an exception // ... } });
To handle success and failure in the same listener, attach an
OnCompleteListener
:
task.addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Task completed successfully AuthResult result = task.getResult(); } else { // Task failed with an exception Exception exception = task.getException(); } } });
Threading
Listeners attached to a thread are run on the application main (UI) thread
by default. When attaching a listener, you can also specify an Executor
that is
used to schedule listeners.
// 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<Runnable>()); task.addOnCompleteListener(executor, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // ... } });
Activity-scoped listeners
If you are listening for task results in an Activity
, you may want to add
activity-scoped listeners to the task. These listeners are removed during
the onStop
method of your Activity so that your listeners are not called
when the Activity is no longer visible.
Activity activity = MainActivity.this; task.addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // ... } });
Chaining
If you use multiple APIs that return Task
, you can chain them together
using a continuation. This helps avoid deeply nested callbacks and consolidates
error handling for chains of tasks.
For example, the method doSomething
returns a Task<String>
but requires
an AuthResult
, which we will get asynchronously from a task:
public Task<String> doSomething(AuthResult authResult) { // ... }
Using the Task.continueWithTask
method, we can chain these two tasks:
Task<AuthResult> signInTask = FirebaseAuth.getInstance().signInAnonymously(); signInTask.continueWithTask(new Continuation<AuthResult, Task<String>>() { @Override public Task<String> then(@NonNull Task<AuthResult> task) throws Exception { // Take the result from the first task and start the second one AuthResult result = task.getResult(); return doSomething(result); } }).addOnSuccessListener(new OnSuccessListener<String>() { @Override public void onSuccess(String s) { // Chain of tasks completed successfully, got result from last task. // ... } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // One of the tasks in the chain failed with an exception. // ... } });
Blocking
If your program is already executing in a background thread you can block a task to get the result synchronously and avoid callbacks:
try { // Block on a task and get the result synchronously. This is generally done // when executing a task inside a separately managed background thread. Doing this // on the main (UI) thread can cause your application to become unresponsive. AuthResult authResult = Tasks.await(task); } catch (ExecutionException e) { // The Task failed, this is the same exception you'd get in a non-blocking // failure handler. // ... } catch (InterruptedException e) { // An interrupt occurred while waiting for the task to complete. // ... }
You can also specify a timeout when blocking a task so that your application does not hang:
try { // Block on the task for a maximum of 500 milliseconds, otherwise time out. AuthResult authResult = Tasks.await(task, 500, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { // ... } catch (InterruptedException e) { // ... } catch (TimeoutException e) { // Task timed out before it could complete. // ... }
Interoperability
A Task
aligns conceptually to several popular Android approaches to managing
asynchronous code, and a Task
can be straightforwardly converted to other
primitives, including the ListenableFuture
and Kotlin coroutines, which are
recommended by AndroidX.
Here's an example using a Task
:
// ... simpleTask.addOnCompleteListener(this) { completedTask -> textView.text = completedTask.result }
Kotlin Coroutine
Usage
Add the following dependency to your project and use the code below to convert
from a Task
.
Gradle (module-level build.gradle
, usually app/build.gradle
)
// Source: https://github.com/Kotlin/kotlinx.coroutines/tree/master/integration/kotlinx-coroutines-play-services implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.7.3'
Snippet
import kotlinx.coroutines.tasks.await // ... textView.text = simpleTask.await() }
Guava ListenableFuture
Add the following dependency to your project and use the code below to convert
from a Task
.
Gradle (module-level build.gradle
, usually app/build.gradle
)
implementation "androidx.concurrent:concurrent-futures:1.2.0"
Snippet
import com.google.common.util.concurrent.ListenableFuture // ... /** Convert Task to ListenableFuture. */ fun <T> taskToListenableFuture(task: Task<T>): ListenableFuture<T> { return CallbackToFutureAdapter.getFuture { completer -> task.addOnCompleteListener { completedTask -> if (completedTask.isCanceled) { completer.setCancelled() } else if (completedTask.isSuccessful) { completer.set(completedTask.result) } else { val e = completedTask.exception if (e != null) { completer.setException(e) } else { throw IllegalStateException() } } } } } // ... this.listenableFuture = taskToListenableFuture(simpleTask) this.listenableFuture?.addListener( Runnable { textView.text = listenableFuture?.get() }, ContextCompat.getMainExecutor(this) )
RxJava2 Observable
Add the following dependency, in addition to the relative async library of
choice, to your project and use the code below to convert from a Task
.
Gradle (module-level build.gradle
, usually app/build.gradle
)
// Source: https://github.com/ashdavies/rx-tasks implementation 'io.ashdavies.rx.rxtasks:rx-tasks:2.2.0'
Snippet
import io.ashdavies.rx.rxtasks.toSingle import java.util.concurrent.TimeUnit // ... simpleTask.toSingle(this).subscribe { result -> textView.text = result }