首页 > 解决方案 > 是否可以在 Mobx 中拥有基于 DateTime.now 的计算属性?

问题描述

我目前正在 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',
  );
});

标签: fluttermobx

解决方案


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

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

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


推荐阅读