TaskCompletionSource

public class TaskCompletionSource<TResult>


Provides the ability to create Task-based APIs.

Use a TaskCompletionSource to set a result or exception on a Task returned from an asynchronous API:

public class MarcoPolo {
  public static Task<String> marco(int delay) {
    TaskCompletionSource<String> taskCompletionSource = new TaskCompletionSource<>();

    new Handler().postDelayed(() -> taskCompletionSource.setResult("polo"), delay);

    return taskCompletionSource.getTask();
  }
}

And then your APIs can be used as any other Task-consuming APIs:

public class MyActivity extends Activity {
  @Override
  public void onStart() {
    super.onStart();

    marco(1000).addOnCompleteListener(
        task -> Log.d(TAG, "got message after one second: " + task.getResult()));
  }
}

Summary

Public constructors

Creates an instance of TaskCompletionSource.

Creates an instance of TaskCompletionSource with a CancellationToken so that the Task can be set to canceled when CancellationToken is canceled.

Public methods

@NonNull Task<TResult>

Returns the Task.

void

Completes the Task with the specified exception.

void
setResult(@Nullable TResult result)

Completes the Task with the specified result.

boolean

Completes the Task with the specified exception, unless the Task has already completed.

boolean
trySetResult(@Nullable TResult result)

Completes the Task with the specified result, unless the Task has already completed.

Public constructors

TaskCompletionSource

public TaskCompletionSource()

Creates an instance of TaskCompletionSource.

TaskCompletionSource

public TaskCompletionSource(@NonNull CancellationToken cancellationToken)

Creates an instance of TaskCompletionSource with a CancellationToken so that the Task can be set to canceled when CancellationToken is canceled.

Public methods

getTask

public @NonNull Task<TResult> getTask()

Returns the Task.

setException

public void setException(@NonNull Exception e)

Completes the Task with the specified exception.

Throws
java.lang.IllegalStateException

if the Task is already complete

setResult

public void setResult(@Nullable TResult result)

Completes the Task with the specified result.

Throws
java.lang.IllegalStateException

if the Task is already complete

trySetException

public boolean trySetException(@NonNull Exception e)

Completes the Task with the specified exception, unless the Task has already completed. If the Task has already completed, the call does nothing.

Returns
boolean

true if the exception was set successfully, false otherwise

trySetResult

public boolean trySetResult(@Nullable TResult result)

Completes the Task with the specified result, unless the Task has already completed. If the Task has already completed, the call does nothing.

Returns
boolean

true if the result was set successfully, false otherwise