Android Dev Summit, October 23-24: two days of technical content, directly from the Android team. Sign-up for livestream updates.

CallbackToFutureAdapter

class CallbackToFutureAdapter
kotlin.Any
   ↳ androidx.concurrent.futures.CallbackToFutureAdapter

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

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

For example, you work with the following async api:

<code>class AsyncApi  {
      interface OnResult {
          void onSuccess(Foo foo);
          void onError(Failure failure);
      }
 
      void load(OnResult onResult) {}
  }
  </code>

Code that wraps it as ListenableFuture would look like:

<code>ListenableFuture&lt;Foo&gt; asyncOperation() {
      return CallbackToFutureAdapter.getFuture(completer -&gt; {
          asyncApi.load(new OnResult() {
              
              public void onSuccess(Foo foo) {
                  completer.set(foo);
              }
 
              
              public void onError(Failure failure) {
                  completer.setException(failure.exception);
              }
          });
          // This value is used only for debug purposes: it will be used in toString()
          // of returned future or error cases.
          return "AsyncApi.load operation";
      });
  }
  </code>

Try to avoid creating references from listeners on the returned Future to the or the passed-in tag object, as this will defeat the best-effort early failure detection based on garbage collection.

Summary

Nested classes

Used to complete the future returned by getFuture

abstract

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

Public methods

static ListenableFuture<T>

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

Public methods

getFuture

@NonNull static fun <T : Any!> getFuture(@NonNull callback: CallbackToFutureAdapter.Resolver<T>): ListenableFuture<T>

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

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