TaskCompletionSource

public class TaskCompletionSource extends Object

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()));
   }
 }
 

Public Constructor Summary

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

Public Method Summary

Task<TResult>
getTask()
Returns the Task.
void
setException(Exception e)
Completes the Task with the specified exception.
void
setResult(TResult result)
Completes the Task with the specified result.
boolean
trySetException(Exception e)
Completes the Task with the specified exception, unless the Task has already completed.
boolean
trySetResult(TResult result)
Completes the Task with the specified result, unless the Task has already completed.

Inherited Method Summary

Public Constructors

public TaskCompletionSource ()

Creates an instance of TaskCompletionSource.

public TaskCompletionSource (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

public Task<TResult> getTask ()

Returns the Task.

public void setException (Exception e)

Completes the Task with the specified exception.

Throws
IllegalStateException if the Task is already complete

public void setResult (TResult result)

Completes the Task with the specified result.

Throws
IllegalStateException if the Task is already complete

public boolean trySetException (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
  • true if the exception was set successfully, false otherwise

public boolean trySetResult (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
  • true if the result was set successfully, false otherwise