How to easily cancel streams in dart/flutter

Sergiu Rosu
Flutter Community
Published in
1 min readMar 12, 2020

Canceling streams is a very good practice, but how do you do it as easy as possible ?

Well we should follow the approach from RX with the dispose bag and create a very simple class which we will be able to mixin with any class we have, let’s call it DisposableWidget ... as everything in flutter is a widget :

class DisposableWidget {

List<StreamSubscription> _subscriptions = [];

void cancelSubscriptions() {
_subscriptions.forEach((subscription) {
subscription.cancel();
});
}

void addSubscription(StreamSubscription subscription) {
_subscriptions.add(subscription);
}

}

easy… now let’s create a extension for the StreamSubscription class, which is returned every time we listen to a stream :

extension DisposableStreamSubscriton on StreamSubscription {
void canceledBy(DisposableWidget widget) {
widget.addSubscription(this);
}
}

easy… now let’s see how we can use this, here is an example with a subscription called from initState :

class CalendarState extends State<Calendar> with DisposableWidget {

@override
void initState() {
super.initState();

_viewModel.setupFromToday();

_viewModel.rebuildStream.listen((rebuild) {
setState(() {

});
}).canceledBy(this);
}
@override
void dispose() {
cancelSubscriptions();
super.dispose();
}
...
...
...

everything we have to do is mixin the DisposableWidget then call canceledBy(this) after each subscription, and of course remember to call cancelSubscriptions() when disposing the widget… and that’s it, a very nice and simple way to never forget to cancel a subscription.

Https://www.twitter.com/FlutterComm

--

--

Sergiu Rosu
Flutter Community

Software engineer, mainly on iOS with Swift, also working with Flutter for iOS and Android.