Home:ALL Converter>Observing streams using Cubit (BLoC library)?

Observing streams using Cubit (BLoC library)?

Ask Time:2021-02-02T17:20:08         Author:kobowo

Json Formatter

TL;DR: Is there a way to listen to streams and emit state using Cubit instead of BLoC?

I'm using the BLoC library for Flutter and we use Cubits for our state management. Everything is working all right so far for interactions to get data or save data but now I need to work with streams. In my case that means watching snapshots from FirebaseFirestore.

I tried searching the internet if there are ways to observe streams for Cubit rather than using BLoC but most of the results point me to BLoC. I've worked with BLoC in another project so I know how to use it for observing streams but I wanted to use Cubit instead if there is a way.

Here is an example of the code I use to observe in FireStore:

@override
  Stream<Either<Failure, List<MTalk>>> watchTalk() async* {
    const path ='path/to/talks';
    yield* firestore
        .collection(path)
        .snapshots()
        .map(
          (snap) => right<Failure, List<MTalk>>(
            snap.docs
                .map(
                    (documentSnapshot) => MTalk.fromFirestore(documentSnapshot))
                .toList(),
          ),
        )
        .onErrorReturnWith((e) {
      if (e is FirestoreException) {
        return left(RetrieveFailure(message: e.message));
      } else {
        return left(UnknownFailure(message: e.toString()));
      }
    });
  }
}

When using BLoC, you could simply use async* and yield to return the state whenever you return data from calling watchTalk() because mapEventToState() is also a Stream that yields State. In the case of Cubit, we use emit(MyState) to get state in the UI and the functions aren't of type Stream. What I wanna know is if we can use Cubit to work with streams.

Author:kobowo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/66006767/observing-streams-using-cubit-bloc-library
yy