Reputation: 2013
I want to cancel a stream, and found that a Stream
cannot be canceled, but a StreamSubsciption
can be canceled. Stream
object has a listen()
method which
Adds a subscription to this stream.
What actually is a subscription? and how do I use it with StreamBuilder
?
From the docs:
A subscription on events from a Stream. When you listen on a Stream using Stream.listen, a StreamSubscription object is returned. The subscription provides events to the listener, and holds the callbacks used to handle the events. The subscription can also be used to unsubscribe from the events, or to temporarily pause the events from the stream.
From what I understand, I think I can use the event
and use it to rebuild my widgets. Is it the right way to do it? or is there is a more correct way to do it?
Upvotes: 3
Views: 6603
Reputation: 9809
If you are using StreamBuilder
, stream subscription and stream cancelling is managed by the framework. The builder
method will be called when new snapshot is available, and when the widget is destroyed, stream subscription is cancelled.
As you wrote, you can create your own StreamSubscription
with listen()
method, and in this case you have to cancel this subscription when you no longer need it, for example in an overridden dispose
method. To do so keep track of subscription in a variable or a member, assuming you have a stream in stream
variable and MyType
is the class which is returned by stream:
StreamSubscription<MyType> myStreamSubscription = stream.listen((value) {
// add code here
});
Then you can use this to manage the stream:
myStreamSubscription.pause();
myStreamSubscription.resume();
myStreamSubscription.cancel();
Upvotes: 5