不理解 MobX-utils fromResource 的行为

Not understanding behavior of MobX-utils fromResource

这是 now() implementation from mobx-utils 的修改版本。根据我的理解,当触发 autorun 函数时,将记录 "initial",然后在 1 秒后记录 Date.now() 的值,然后每秒一次又一次地记录 Date.now()

function createIntervalTicker(interval) {
    let subscriptionHandle
    return fromResource(
        sink => {
            subscriptionHandle = setInterval(
                () => sink(Date.now()),
                interval
            );
        },
        () => {
            clearInterval(subscriptionHandle);
        },
        'initial'
    );
}

autorun(() => {
  console.log(createIntervalTicker(1000).current())
})

但是,我 "initial" 每秒一次又一次地注销。 Date.now() 的值永远不会被记录。

好像调用sink(Date.now())时只是触发了autorun函数,并没有更新current()返回的值。

如有任何建议,我将不胜感激。提前致谢。

mobx@3.1.16 mobx-utils@2.0.2

您的代码会创建一个新的可观察对象,并在每次执行 autorun 时将其值传递给 console.log。因此,您总是会在浏览器控制台中看到 initial:mobx 跟踪对初始 observable 的更改,但 console.log 在每次反应时都会收到新的 observable。

解决方案:存储对初始可观察对象的引用并重用它

const ticker = createIntervalTicker(1000);
autorun(() => {
  console.log(ticker.current())
})