Search code examples
flutterblocflutter-bloc

Flutter Bloc emit how to handle when the stream is done


await emit.onEach(
// This stream, how do you handle when this stream is done?
stream, 
onData: (data){

      }
);

Normally on Flutter Stream we have a callback onDone, but on emit onEach or forEach flutter bloc callback, onDone do not exists.

Currently my solution is

final broadCastStream = stream.asBroadcastStream();
broadCastStream.listen(
          (event) {},
          onDone: () {
          // Handle on Done
          },
        );
await emit.onEach(
broadCastStream, 
onData: (data){

      }
);

I want to emit a new state when the stream is done / canceled / errors


Solution

  • The future completes when the onDone is called. So you can do something like this

    emit
    .onEach(stream, onData: (val) => print(val))
    .then((value) => print('onDone'))
    .onError((error, stackTrace) => print('error'));