Can Dart Streams emit a value if the stream is not done within a duration?


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 yielding 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?


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();

Answered By – mentoc3000

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *