Propagates notification that operations should be canceled.
Developers writing methods that return a Task should take aCancellationToken
as a parameter if they wish to make the Task cancelable (see below code snippet). A
CancellationToken
can only be created by creating a new instance of
CancellationTokenSource
.
CancellationToken
is immutable and must be canceled by callingCancellationTokenSource.cancel()
on theCancellationTokenSource
that creates it. It can only be canceled once. If canceled, it should not be passed to future
operations.
WhenCancellationTokenSource.cancel()
is called, all the Tasks with theCancellationToken
from thatCancellationTokenSource
will be canceled. This operation only flags those Tasks as canceled, and the API author is
responsible for stopping whatever the Task is actually doing to free up the resources.
CancellableTask
example:
public Task<Integer> doSomething(CancellationToken token) { // Attach a listener that will be called once cancellation is requested. token.onCanceledRequested(new OnTokenCanceledListener() { @Override public void onCanceled() { // Some other operations to cancel this Task, such as free resources... } }); final TaskCompletionSource<Integer> tcs = new TaskCompletionSource<>(token); // do something... } CancellationTokenSource cts = new CancellationTokenSource(); Task<Integer> task = doSomething(cts.getToken()); cts.cancel();Cancellable
Task
example in
Activity
context:
public class MyActivity extends Activity { //... @Override public void onStart() { super.onStart(); // Typically use one cancellation source per lifecycle. cancellationSource = new CancellationTokenSource(); // That source's token can be passed to multiple calls. doSomethingCancellable(cancellationSource.getToken()) .onSuccessTask(result -> doSomethingElse(result, cancellationSource.getToken())); } @Override public void onStop() { super.onStop(); cancellationSource.cancel(); } }
Public Constructor Summary
Public Method Summary
abstract boolean |
isCancellationRequested()
Checks if cancellation has been requested from the
CancellationTokenSource .
|
abstractCancellationToken |
onCanceledRequested(OnTokenCanceledListener
listener)
Adds an
OnTokenCanceledListener
to thisCancellationToken .
|
Inherited Method Summary
Public Constructors
publicCancellationToken()
Public Methods
public abstract boolean isCancellationRequested()
Checks if cancellation has been requested from theCancellationTokenSource
.
Returns
true
if cancellation is requested,false
otherwise
public abstractCancellationToken onCanceledRequested(OnTokenCanceledListener listener)
Adds anOnTokenCanceledListener
to thisCancellationToken
.
Parameters
listener | the listener that will fire once the cancellation request succeeds. |
---|