Search code examples
flutterdartblocstate-managementcubit

Flutter Bloc Listen to stream and emit state with Cubit


How can I listen to stream and emit state with Cubit?

With Bloc we can do something like this:

    on<VideoStreamPlayPauseEvent>(
      (event, emit) async {
        if (event.play) {
          await emit.forEach(
            videoStreamingRepo.videoDataStream,
            onData: (VideoData videoStreamData) => VideoStreamState(
              currentFrame: videoStreamData,
              isPlaying: true,
            ),
          );
        }

Solution

  • You should listen to the stream using listen() and based on the event you can emit the desired state.

    yourstream.listen((event) {
          if (event.play)
              emit(First State)
          else
              emit(Second State)
        });
    

    Extra: Based on the demand of questioner

    To Stop listening to stream:
    StreamSubscription<Map<PlaceParam, dynamic>> subscription;
    subscription = yourstream.listen((event) {
          if (event.play)
              emit(First State)
          else
              emit(Second State)
    
          ...
       
          subscription.cancel(); 👈 cancel this way
        });