如何自动quot”取消流订阅?

发布于 2025-02-13 07:13:34 字数 524 浏览 0 评论 0原文

我有一个具有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一腔孤↑勇 2025-02-20 07:13:34

使用 flutter钩子 usestream ,可以订阅流(就像您在in> initstate中一样),返回其当前值,并在当时自动取消订阅小部件生命周期已完成(就像您将dispose中放置一样)。

雷米(Remi)的技术非常好...同一个人写了提供商和Riverpod。

Use Flutter Hooks useStream, which can subscribe to a stream (like you would put in initState), return its current value, and automatically cancels the subscription when the widget lifecycle is complete (like you would put in dispose).

Very good technology from Remi... the same guy who wrote Provider and RiverPod.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文