How to handle an Exceptions in a Stream in Flutter?

120 Views Asked by At

I'm subscribing to a collection in firestore and I would like to handle errors firestore can throw in the snapshots stream. The errors should be catched and emit a left(UnexpectedFailure) in the stream and shouldn't terminate the stream. How can I achieve this?

Here is my code sample:

@override
  Stream<Either<Failure, List<Foo>>> getStream() {
    String uid = firebaseAuth.currentUser!.uid;
    return firestore
        .collection(FOO_COLLECTION)
        .doc(uid)
        .collection(FOO_COLLECTION)
        .snapshots()
        .map(
      (querySnapshot) {
        try {
          return right<Failure, List<Foo>>(querySnapshot.docs
              .map((doc) => FooDto.fromFirestore(doc).toDomain())
              .toList());
        } catch (e) {
          return left(UnexpectedFailure(e));
        }
      },
    );
  }
}

Any answers/comments are highly appreciated!

0

There are 0 best solutions below