Do I need to cancel Stream<QuerySnapshot> (flutter)
Asked Answered
E

2

8

I am listening to a collection of documents in firestore (as part of a chat app). I am doing this by using a service, which creates a Stream<QuerySnapshot> as follows:

_snapshots$ = Firestore.instance.collection('messages').orderBy('date',descending: false).snapshots()

I then create a StreamBuilder as follows:

return StreamBuilder<List<Message>>(
        stream: widget.chatService.messages$,
        builder: (context, snapshot) => (snapshot.hasData)
...

I am wondering if I need to detach this stream in the dispose method containing the StreamBuilder widget. I don't know much about Streams and StreamBuilders, so I'm not sure how to do this, but I really want to avoid any memory leaks.

Enumeration answered 6/2, 2020 at 3:49 Comment(0)
D
10

You are right to worry about this, but StreamBuilder will do all the heavy lifting for you, including subscribing and unsubscribing, so you don't have to worry about it if StreamBuilder is the only place where your Stream is being listened to. But if you are listening to the Stream yourself, then you will have to cancel the subscription on a StatefulWidget dispose method.

Doxy answered 6/2, 2020 at 3:54 Comment(1)
For those wondering, it's like final subscription = stream.listen(...); and then subscription.cancel();. I use this approach in Providers and pass a future to the widgets (instead of a stream). So the provider controls the rebuilds based on other conditions.Bathelda
R
4

Someone should correct me if I'm wrong, but I think that's the point of the StreamBuilder class: Looking at the source code, it seems to unsubscribe on dispose() naturally.

Raquel answered 6/2, 2020 at 3:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.