Issue
I am working on a Flutter app using blocs to control the state of the view. I want to call and external API and if it responds quickly, show the results right away by yield
ing the result state. However, if the call takes more than, say, 5 seconds, I would like to yield a state indicating that the response is taking a while while still waiting for the API to return. How can I do this with Dart Streams, either natively or with RxDart?
Solution
This can be accomplished using Stream.timeout
. Thanks @pskink!
Stream<String> delayedCall() async* {
yield 'Waiting';
final apiCall = Future.delayed(Duration(seconds: 5)).then((_) => 'Complete');
yield* Stream.fromFuture(apiCall).timeout(
Duration(seconds: 3),
onTimeout: (eventSink) => eventSink.add('Still waiting'),
);
}
void main() {
final stream = delayedCall();
stream.listen(print);
}
Answered By – mentoc3000
Answer Checked By – Marie Seifert (FlutterFixes Admin)