CallbackToFutureAdapter

public final class CallbackToFutureAdapter
extends Object

java.lang.Object
   ↳ androidx.concurrent.futures.CallbackToFutureAdapter


A utility useful for adapting interfaces that take callbacks into interfaces that return ListenableFuture.

It also provides additional safety checks, failing the future if it will never complete.

For example, you work with the following async api:

class AsyncApi  {
     interface OnResult {
         void onSuccess(Foo foo);
         void onError(Failure failure);
     }

     void load(OnResult onResult) {}
 }
 

Code that wraps it as ListenableFuture would look like:

{@code
 ListenableFuture asyncOperation() {
     return CallbackToFutureAdapter.getFuture(completer -> {
         asyncApi.load(new OnResult() {

Summary

Nested classes

class CallbackToFutureAdapter.Completer<T>

Used to complete the future returned by CallbackToFutureAdapter.getFuture(CallbackToFutureAdapter.Resolver)  

interface CallbackToFutureAdapter.Resolver<T>

This interface should be implemented by the object passed into CallbackToFutureAdapter.getFuture(Resolver)

Public methods

static <T> ListenableFuture<T> getFuture(Resolver<T> callback)

Returns a Future that will be completed by the CallbackToFutureAdapter.Completer provided in CallbackToFutureAdapter.Resolver.attachCompleter(Completer).

Inherited methods

Public methods

getFuture

public static ListenableFuture<T> getFuture (Resolver<T> callback)

Returns a Future that will be completed by the CallbackToFutureAdapter.Completer provided in CallbackToFutureAdapter.Resolver.attachCompleter(Completer).

The provided callback is invoked immediately inline. Any exceptions thrown by it will fail the returned Future.

Parameters
callback Resolver

Returns
ListenableFuture<T>