Search code examples
mobxmobx-utils

Not understanding behavior of MobX-utils fromResource


This is a modified version of the now() implementation from mobx-utils. From my understanding, when the autorun function is triggered, "initial" would be logged, then after 1 second, the value of Date.now(), then Date.now() again and again every second.

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

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

However, I am getting "initial" logged out every second again and again. The value of Date.now() is never logged.

It seems that when sink(Date.now()) is called, it is only triggering the the autorun function, but not updating the value returned by current().

I would appreciate any advice. Thanks in advance.

[email protected] [email protected]


Solution

  • Your code creates a new observable and passes its value to console.log each time autorun is executed. Hence, you always see initial in the browser console: mobx tracks changes to the initial observable, but console.log receives new observable on each reaction.

    Solution: store a reference to the initial observable and reuse it

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