skip to Main Content
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

2

Answers


  1. 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'));
    
    Login or Signup to reply.
  2. You can consider directly listening to the stream. And use onError, onDone and cancelOnError callbacks.

    From the doc : Stream-listen

    StreamSubscription<T> listen(
    void onData(
    T event
    )?,
    {Function? onError,
    void onDone()?,
    bool? cancelOnError}
    )
    

    Example :

    final streamSubscription = stream.listen(
      (data) {
        // handle data
      },
      onError: (error) {
        // handle error
      },
      onDone: () {
        // handle completion
        emit(MyState(isStreamCompleted: true));
      },
    );
    
    await emit.onCancel(() {
      streamSubscription.cancel();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search