TaskCompletionSource

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 functions

Task<TResult!>

Returns the Task.

Unit

Completes the Task with the specified exception.

Unit
setResult(result: TResult?)

Completes the Task with the specified result.

Boolean

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

Boolean
trySetResult(result: TResult?)

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

Public constructors

TaskCompletionSource

TaskCompletionSource()

Creates an instance of TaskCompletionSource.

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 functions

getTask

fun getTask(): Task<TResult!>

Returns the Task.

setException

fun setException(e: Exception): Unit

Completes the Task with the specified exception.

Throws
java.lang.IllegalStateException

if the Task is already complete

setResult

fun setResult(result: TResult?): Unit

Completes the Task with the specified result.

Throws
java.lang.IllegalStateException

if the Task is already complete

trySetException

fun trySetException(e: Exception): Boolean

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

fun trySetResult(result: TResult?): Boolean

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