Skip to content

Instantly share code, notes, and snippets.

@patkujawa-wf
Created September 26, 2018 03:29
Show Gist options
  • Save patkujawa-wf/f4126c371cb7a2ec0db4578547848adc to your computer and use it in GitHub Desktop.
Save patkujawa-wf/f4126c371cb7a2ec0db4578547848adc to your computer and use it in GitHub Desktop.
Example CancellationToken[Source] a la .net. Provides a way to signal that an operation has been canceled
import 'package:w_common/func.dart';
/// Provides a way to signal that an operation has been canceled.
///
/// Typically, the consumer creates a [CancellationTokenSource] and then passes
/// the [token] to another operation. The consumer can then call [cancel],
/// while the operation can only check if it has been canceled.
///
/// FUTURE: If we want a stream to listen for when a cancellation has happened,
/// use CancelableCompleter from the async package instead.
class CancellationTokenSource {
CancellationToken _token;
bool _isCancellationRequested = false;
CancellationTokenSource() {
_token = new CancellationToken(() {
return _isCancellationRequested;
});
}
CancellationToken get token => _token;
/// Signal to the [token] bearer that they should cancel
void cancel() {
_isCancellationRequested = true;
}
}
/// Provides a way to check if an operation should be canceled.
class CancellationToken {
final Func<bool> isCancellationRequested;
CancellationToken(this.isCancellationRequested);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment