如何在 Mobx flutter 中观察其他 class 的字段变量?

How to observe field variable of other class in Mobx flutter?

我正在使用 flutter Mobx 进行状态管理。 我有一个简单的 class:-

class A {
  int x;
  A(this.x);
 }

我如何观察 x 是否在另一个 Mobx 商店的 class 内发生变化:-

class MyStore extends _MyStore  with _$MyStore  {
  Subs(A a) : super(a);
}

abstract class _MyStore  with Store {
  @observable
  A a;
  _Subs(this.a)
}

我想MyStore观察a.x。

有可能吗,如果有怎么办?

我不确定这是否有用,因为它是 Javascript/Typescript,但这就是我要做的 :

class Foo {
  @observable name = 'foo'
}

class Bar {
  foo: Foo

  constructor(instanceOfFoo) {
    this.foo = instanceOfFoo

    autorun(() => {
      // Logs foo name when it changes
      console.log(this.foo.name)
    })

    reaction(
      () => this.foo.name,
      () => {
        // Logs foo name when it changes
        console.log(this.foo.name)
      }
    )
  }

  @observable
  name = 'bar'

  @computed
  get fooNamePlusBarName {
    // recomputes automatically whenever foo or bar name changes
    return this.foo.name + this.name
  }
}

基本上你将 Foo 实例传递给 Bar 构造函数(或者如果它适合你就使用导入的单例),那么你有 3 个选项:computedreactionautorun

我 运行 前几天使用 flutter mobx ^1.2.1+3 (dart) 和 flutter_mobx ^1.1.0+2.

我首先想到的是注释相关字段,即 x@observable 属性。但它似乎在商店外没有效果class。 所以你必须使用 Observable class.

来观察字段

要使其正常工作,您的代码应如下所示:

class A {
  //replace with less verbose "var"
  Observable<int> x = Observable(0);
  A(this.x);
 }

class MyStore extends _MyStore  with _$MyStore  {
  Subs(A a) : super(a);
}

abstract class _MyStore  with Store {
  
  A a;
  _Subs(this.a)
  
  //Will be calculated whenever a change to a.x is observed.
  @computed
  int get xSquare => a.x.value * a.x.value;
}

如您所见,我从 a 中删除了 observable 属性,因为如果您想对商店中 a.x 的更改做出反应,则不需要观察它。您可能注意到您必须使用 .value.

访问可观察对象的值

这应该总结了您如何在商店内部观察商店外部的 class 字段。