3

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,
            ),
          );
        }
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
Soliev
  • 1,180
  • 1
  • 1
  • 12

2 Answers2

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

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
2

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

Soliev
  • 1,180
  • 1
  • 1
  • 12