Created
March 30, 2023 04:42
-
-
Save take4blue/9a14cee3dac7a339be85223a004a5938 to your computer and use it in GitHub Desktop.
Future.timeoutサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Future<int> test(String name) async { | |
for (int i = 0; i < 3; i++) { | |
await Future.delayed(const Duration(seconds: 1)); | |
print("[$name] count = $i"); | |
} | |
print("[$name] test end"); | |
return 3; | |
} | |
void main(List<String> args) async { | |
{ | |
/// 1秒おきにprintをする | |
final future = test("1"); | |
// futureの処理完了時にプリント | |
future.then((value) => print("future end $value"), | |
onError: (Object error) => print("error")); | |
// timeoutの設定をしてFutureが止まるかどうかの確認 | |
future.timeout( | |
const Duration(seconds: 2), | |
onTimeout: () { | |
print("timeout"); | |
return 10; | |
}, | |
).then((value) => "future timeout end $value"); | |
} | |
{ | |
/// 1秒おきにprintをする | |
final future = test("2"); | |
// timeoutの設定をしてFutureが止まるかどうかの確認 | |
try { | |
await future.timeout( | |
const Duration(seconds: 2), | |
); | |
} catch (e) { | |
print(e); | |
} finally { | |
print("finally"); | |
} | |
} | |
{ | |
/// 1秒おきにprintをする | |
final future = test("3"); | |
// timeoutの設定をしてFutureが止まるかどうかの確認 | |
try { | |
final ans = await future.timeout( | |
const Duration(seconds: 2), | |
onTimeout: () => 5, | |
); | |
print("timeout end $ans"); | |
} catch (e) { | |
print(e); | |
} finally { | |
print("finally"); | |
} | |
} | |
print("main end"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment