Skip to content

Instantly share code, notes, and snippets.

@take4blue
Created March 30, 2023 06:57
Show Gist options
  • Save take4blue/11952ded1e34d53cf168b02add9a3635 to your computer and use it in GitHub Desktop.
Save take4blue/11952ded1e34d53cf168b02add9a3635 to your computer and use it in GitHub Desktop.
非同期関数を途中で止める例
import 'package:async/async.dart';
import 'dart:async';
Future<int> test(String name, {List<bool>? cancel}) async {
for (int i = 0; i < 4; i++) {
await Future.delayed(const Duration(seconds: 1));
print("[$name] count = $i");
if (cancel != null && cancel[0]) {
print("[$name] canceled");
break;
}
}
print("[$name] test end");
return 3;
}
class Test {
Test(this.name);
final String name;
final _command = CancelableCompleter<int>();
void start() {
_command.complete(_test(name));
}
void cancel() {
_command.operation.cancel();
}
bool get isCompleted => _command.isCompleted;
Future<int> get result => _command.operation.value;
Future<int> _test(String name) async {
for (int i = 0; i < 4; i++) {
await Future.delayed(const Duration(seconds: 1));
print("[$name] count = $i");
if (_command.isCanceled) {
print("[$name] canceled");
return 100;
}
}
print("[$name] test end");
return 3;
}
}
void main(List<String> args) {
{
test("0");
}
{
final List<bool> cancel = <bool>[false];
test("1", cancel: cancel);
Future.delayed(const Duration(seconds: 2), () {
print("[1] cancel");
cancel[0] = true;
});
}
Future(() async {
final test = Test("2");
test.start();
print("test[2] = ${await test.result}");
});
Future(() async {
final test = Test("3");
test.start();
Future.delayed(const Duration(seconds: 2), () {
print("[3] cancel");
test.cancel();
});
print("test[3] = ${await test.result}");
});
print("main end");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment