Dart stream .asBroadcastStream memory leak

为君一笑 提交于 2020-03-04 15:34:01

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/60470365/dart-stream-asbroadcaststream-memory-leak

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!