如何自动quot”取消流订阅?
我有一个具有streamsubscript的DART模型:
class CounterPageModel {
CounterPageModel() {
subscription = Services.resetCounter.listen(resetCounter);
}
late StreamSubscription<bool> subscription;
如果我了解StreamSubscription,则在处理streamDescription
实例时,它不会调用cance
。那是对的吗?如果是这样,是否有一种简单的方法来取消我的模型时?
我编写了一个简单的DISCOSE
函数,当要处理模型时可以取消订阅时可以调用,但是感觉一定有一个更标准的方法? (例如,为streamSubscription编写包装器,该包装量 cance> cance 当streamsubscription被处置时?但是我不知道那会是什么样。)
I have a dart model that has a StreamSubscription:
class CounterPageModel {
CounterPageModel() {
subscription = Services.resetCounter.listen(resetCounter);
}
late StreamSubscription<bool> subscription;
If I'm understanding StreamSubscription, it doesn't call cancel
when the StreamDescription
instance is disposed. Is that correct? If so, is there a simple way to cancel the subscription when my model is disposed?
I wrote a simple dispose
function that I can call when the model is about to be disposed that would cancel the subscription, but it feels like there must be a more standard way? (E.g., write a wrapper for StreamSubscription that calls cancel
when StreamSubscription is disposed? But I don't know what that would look like.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 flutter钩子
usestream
,可以订阅流(就像您在in> initstate
中一样),返回其当前值,并在当时自动取消订阅小部件生命周期已完成(就像您将dispose
中放置一样)。雷米(Remi)的技术非常好...同一个人写了提供商和Riverpod。
Use Flutter Hooks
useStream
, which can subscribe to a stream (like you would put ininitState
), return its current value, and automatically cancels the subscription when the widget lifecycle is complete (like you would put indispose
).Very good technology from Remi... the same guy who wrote Provider and RiverPod.