In our Flutter application we have memory leaks and streams not being closed. We traced the source to code such as:
Rx.combineLatest(...).asBroadcastStream()
The result of RxDart .combineLatest()
is a single-subscription stream. Adding .asBroadcastStream()
makes the stream conveniently available to our various Flutter displays. However when these displays are closed the streams being combined are still active.
From the .asBroadcastStream()
documentation:
The returned stream will subscribe to this stream when its first subscriber is added, and will stay subscribed until this stream ends, or a callback cancels the subscription.
So by design the stream exists until explicitly cancelled. To cancel the subscription when the last listener cancels use:
Rx.combineLatest(...).asBroadcastStream( onCancel: (sub) => sub.cancel() )
There is further discussion in Stream.asBroadcastStream - Easy to cause leaks, what is the rationale? #26686