RINDAMAN
RINDAMAN

Reputation: 53

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

Upvotes: 0

Views: 1448

Answers (2)

krishnaacharyaa
krishnaacharyaa

Reputation: 25070

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

Upvotes: 0

Rahul
Rahul

Reputation: 4341

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

Upvotes: 1

Related Questions