覆盖 ChangeNotifier 中的 dispose 方法

huangapple go评论93阅读模式
英文:

Override dispose method in a ChangeNotifier

问题

我有以下的模型

class SelectorModel with ChangeNotifier {
    .... // 与模型相关的内容
}

在我的模型内部,我使用以下方式获取Firestore文档的流:

_subscription = Firestore.instance   // _subscription在上面被定义为一个iVar
      .collection('myCollection')
      .snapshots()
  .listen((querySnapshot)  {
    _jobs = querySnapshot.documents;
    callingMethod('');  // 被调用的方法在我的模型内部
  });

我需要一种方法来释放 _subscription,以便当我的Firestore数据库发生更改时,不会尝试在我的模型已经被释放时调用 callingMethod()

我正在寻找的方法几乎类似于以下的ChangeNotifier方法:

@override
void dispose() {
    super.dispose();
    _subscription.cancel();
}

我查看了Provider的文档,但没有找到相关内容。

感谢任何帮助!

英文:

I have the following model

class SelectorModel with ChangeNotifier {
    .... // stuff relating to the model
}

and inside my model I'm getting a stream of Firestore documents using the following:

_subscription = Firestore.instance   // _subscription is defined as an iVar above
      .collection('myCollection')
      .snapshots()
  .listen((querySnapshot)  {
    _jobs = querySnapshot.documents;
    callingMethod('');  // the method being called is inside of my model
  });

I need a way to dispose of the _subsciption so that when a change occurs in my Firestore database, it will not attempt to call callingMethod() when my model has already been disposed.

What I'm looking for is a method almost like the following for a ChangeNotifier:

@override
void dispose() {
    super.dispose();
    _subscription.cancel();
}

I looked through the provider docs but could not find anything.

Thanks for any help!

答案1

得分: 1

你可以这样做,如果我理解你的意思

_subscription = Firestore.instance
          .collection('myCollection')
          .snapshots()
      .listen((querySnapshot)  {
        _jobs = querySnapshot.documents;
        callingMethod('');  // 被调用的方法在我的模型内部
       _subscription.cancel();
      });
英文:

You can do it like that if i understand you

_subscription = Firestore.instance   // _subscription is defined as an iVar above
      .collection('myCollection')
      .snapshots()
  .listen((querySnapshot)  {
    _jobs = querySnapshot.documents;
    callingMethod('');  // the method being called is inside of my model
   _subscription.cancel();
  });

huangapple
  • 本文由 发表于 2020年1月4日 00:57:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582413.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定