Home > Software engineering >  Flutter - Firebase Firestore as a service
Flutter - Firebase Firestore as a service

Time:11-10

In Flutter, I want to create a class that serves as a service to Firebase Firestore DB.
So that instead of listening to a document change directly from my controller / model like so:

StreamSubscription<DocumentSnapshot> listener = FirebaseFirestore.instance
  .collection('products')
  .doc(productId)
  .snapshots()
  .listen(_onProductUpdate);

I'll have a method in my service, that will delegate that stream, like so:

Stream<Product> listenToProduct(String productId) {
  return FirebaseFirestore.instance.collection('products')
    .doc(productId)
    .snapshots()
    .map((snapshot) => Product.fromJson(snapshot.data()!));
}

And my controller / model will use it like so:

GetIt.I<FirestoreService>()
    .listenToProduct(productId)
    .listen(_onProductUpdate);

My only issue is that I don't know how to cancel the subscription listener in the second case.
I mean, when listening directly to Firestore, I can use:

listener.cancel();

How do I achieve this using my Firestore service?

CodePudding user response:

Create a variable of static StreamSubscription? subscription; and reference the listen to that variable, subscription = reference.onValue.listen... and then you can use

if (subscription != null) {
      subscription!.cancel();
    }

to cancel it

  • Related