Dart 流 .asBroadcastStream 内存泄漏
Dart stream .asBroadcastStream memory leak
在我们的 Flutter 应用程序中,我们存在内存泄漏和流未关闭的问题。我们溯源到如下代码:
Rx.combineLatest(...).asBroadcastStream()
RxDart .combineLatest()
的结果是单订阅流。添加 .asBroadcastStream()
可以方便地为我们的各种 Flutter 显示提供流。然而,当这些显示关闭时,正在组合的流仍然有效。
来自 .asBroadcastStream()
文档:
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.
因此,根据设计,流一直存在,直到被明确取消。要在最后一个侦听器取消时取消订阅,请使用:
Rx.combineLatest(...).asBroadcastStream( onCancel: (sub) => sub.cancel() )
Stream.asBroadcastStream - Easy to cause leaks, what is the rationale? #26686
中有进一步的讨论
在我们的 Flutter 应用程序中,我们存在内存泄漏和流未关闭的问题。我们溯源到如下代码:
Rx.combineLatest(...).asBroadcastStream()
RxDart .combineLatest()
的结果是单订阅流。添加 .asBroadcastStream()
可以方便地为我们的各种 Flutter 显示提供流。然而,当这些显示关闭时,正在组合的流仍然有效。
来自 .asBroadcastStream()
文档:
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.
因此,根据设计,流一直存在,直到被明确取消。要在最后一个侦听器取消时取消订阅,请使用:
Rx.combineLatest(...).asBroadcastStream( onCancel: (sub) => sub.cancel() )
Stream.asBroadcastStream - Easy to cause leaks, what is the rationale? #26686
中有进一步的讨论