Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart timeout on await Future

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();
like image 212
TSR Avatar asked Jun 14 '19 07:06

TSR


People also ask

How do you wait for Future to complete Dart?

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.

How is Whencompleted () different from then () in 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.

How do you cancel Future darts?

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.


1 Answers

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');
  });
}
like image 64
Alexandre Ardhuin Avatar answered Nov 15 '22 09:11

Alexandre Ardhuin