skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    My final result is

    enum ConnectionStatus { unknown, connected, disconnected, poor }
    
    class ConnectionCubit extends Cubit<ConnectionStatus> {
      ConnectionCubit() : super(ConnectionStatus.unknown);
      late final StreamSubscription<ConnectivityResult> _streamSubscription;
    
      void checkConnection() async {
        _streamSubscription = Connectivity().onConnectivityChanged.listen((event) {
          if (event == ConnectivityResult.mobile ||
              event == ConnectivityResult.wifi) {
            emit(ConnectionStatus.connected);
          } else {
            emit(ConnectionStatus.disconnected);
          }
        });
      }
    
      @override
      Future<void> close() {
        _streamSubscription.cancel();
        return super.close();
      }
    
    

  2. 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
        });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search