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()));
}
}
|
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.
|
| Task<TResult> |
getTask()
Returns the Task.
|
| void | |
| 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.
|
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.
Returns the Task.
Completes the Task with the specified exception.
| IllegalStateException | if the Task is already complete |
|---|
Completes the Task with the specified result.
| IllegalStateException | if the Task is already complete |
|---|
Completes the Task with the specified exception, unless the Task has already completed. If the Task has already completed, the call does nothing.
true if the exception was set successfully, false
otherwiseCompletes the Task with the specified result, unless the Task has already completed. If the Task has already completed, the call does nothing.
true if the result was set successfully, false
otherwise