How to make a await future
not last more than 5 seconds ?
I need it because in some networking operation, the connection is sometimes producing silent error. Hence my client just wait for hours with no response. Instead, I want it trigger an error when the clients waits for more than 5 seconds
My code can trigger the error but it is still waiting
Future shouldnotlastmorethan5sec() async {
Future foo = Future.delayed(const Duration(seconds: 10));;
foo.timeout(Duration(seconds: 5), onTimeout: (){
//cancel future ??
throw ('Timeout');
});
await foo;
}
Future test() async {
try{
await shouldnotlastmorethan5sec(); //this shoud not last more than 5 seconds
}catch (e){
print ('the error is ${e.toString()}');
}
}
test();
To prevent multiple awaits, chaining futures in . then(), you can simply use Future. wait([]) that returns an array of results you were waiting for. If any of those Futures within that array fails, Future.
. whenComplete will fire a function either when the Future completes with an error or not, instead . then will fire a function after the Future completes without an error.
Many of you know that you can't cancel a Future in Dart, but you can cancel a subscription to a Stream. So one way you could handle this situation is to rewrite getData() to return a Stream instead.
When you call Future.timeout you need to use the return value to get the correct behaviour. In your case:
Future shouldnotlastmorethan5sec() {
Future foo = Future.delayed(const Duration(seconds: 10));
return foo.timeout(Duration(seconds: 5), onTimeout: (){
//cancel future ??
throw ('Timeout');
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With