The Task APIs

  • The Task API is the standard for handling asynchronous operations in Google Play services, offering a flexible replacement for PendingResult.

  • You can handle Task results by attaching listeners for success (OnSuccessListener), failure (OnFailureListener), or both (OnCompleteListener).

  • Listeners for Task run on the main thread by default, but you can specify an Executor to schedule them on background threads.

  • Activity-scoped listeners for Task automatically manage their lifecycle and are removed when the Activity stops.

  • You can chain Task objects using continuations to manage complex asynchronous flows and avoid nested callbacks.

  • You can block a background thread and wait for a Task to complete synchronously using Tasks.await().

  • Task is designed for interoperability and can be converted to and from other asynchronous patterns like Kotlin coroutines and ListenableFuture.

The Task API is the standard way to handle asynchronous operations in Google Play services. It provides a powerful and flexible way to manage asynchronous calls, replacing the older PendingResult pattern. With Task, you can chain multiple calls, handle complex flows, and write clear success and failure handlers.

Handle task results

Many APIs in Google Play services and Firebase return a Task object to represent asynchronous operations. For example, FirebaseAuth.signInAnonymously() returns a Task<AuthResult> which represents the result of the sign-in operation. The Task<AuthResult> indicates that when the task completes successfully, it will return an AuthResult object.

You can handle the result of a Task by attaching listeners that respond to successful completion, failure, or both:

Task<AuthResult> task = FirebaseAuth.getInstance().signInAnonymously();

To handle a successful task completion, attach an OnSuccessListener:

task.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
    @Override
    public void onSuccess(AuthResult authResult) {
        // Task completed successfully
        // ...
    }
});

To handle a failed task, attach an OnFailureListener:

task.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull