【问题标题】:Is it possible to have a computed property based on DateTime.now in Mobx?是否可以在 Mobx 中拥有基于 DateTime.now 的计算属性?
【发布时间】:2021-06-03 17:31:28
【问题描述】:

我目前正在 Dart/Flutter 中尝试这个,但我认为这个概念在其他语言中是相同的。

考虑到 'expires' 收到一个表示从现在起 2 天的日期,因此 'expired' 为 true,并且应在 2 天过去后更改为 false。

@observable
DateTime expires;

@computed
bool get expired =>
      expires == null ||
      expires.difference(DateTime.now()).inSeconds <= 0;

在运行应用程序时,此属性不会从 true 变为 false,但在我的单元测试中,它确实如此,这就是为什么我不知道这是否可能。

单元测试供参考:

test('when expires pass its due date, it should trigger expired',
    () async {
  state.changeExpires(
    DateTime.now().add(const Duration(seconds: 3)),
  );

  expect(
    state.hasTokenExpired,
    isFalse,
    reason:
        'because expires ${state.expires.toIso8601String()} should be in the interval expected to not be expired',
  );

  await Future.delayed(const Duration(seconds: 3));

  expect(
    state.hasTokenExpired,
    isTrue,
    reason:
        'because expired ${state.expires.toIso8601String()} has not expired',
  );
});

【问题讨论】:

    标签: flutter mobx


    【解决方案1】:

    对于 JS,有一个不错的 utils 库 mobx-utils 具有类似的功能 now(),它将更新所有观察者、反应等。

    https://github.com/mobxjs/mobx-utils/blob/master/src/now.ts

    也许你可以尝试为 Dart 实现它。

    【讨论】:

    • 你为我指明了正确的方向,我从 mobx 的颤振 repo 中获得的示例与 now.ts 中的示例相似。谢谢!
    【解决方案2】:

    解决方案可以通过流来实现。这是一个例子和direct reference from mobx's flutter repository

    class TimeStore = _TimeStoreBase with _$TimeStore;
    
    abstract class _TimeStoreBase with Store {
      @observable
      DateTime expired = DateTime.now();
      @observable
      ObservableStream<DateTime> _time = Stream.periodic(Duration(seconds: 1))
          .map((_) => DateTime.now())
          .asObservable();
    
      @computed
      DateTime get now => _time.value ?? DateTime.now();
    
      @computed
      bool get expired => expires != null && expires.difference(now).inSeconds <= 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-06
      • 2021-10-10
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2011-02-23
      相关资源
      最近更新 更多