Closed ivan-kleshnin closed 5 years ago
Hi!
You can pass the { lazy: true }
flag to do not run it immediately. If you pass it you have to call the returned reaction once later to kick-off the observation process. See the related docs section.
import { observable, observe } from '@nx-js/observer-util';
const counter = observable({ num: 0 });
+ // does not call countLogger
const countLogger = observe(() => console.log(counter.num), { lazy: true });
// this does not react yet, the returned reaction has to run once to kick off the observation process
counter.num++;
// this runs the reaction and starts the observation
countLogger()
// this also runs the reaction (observation is already started)
counter.num++;
This is useful when you don't own the control flow of the program. See my other lib (react-easy-state) for a real life example of the usage.
EDIT: you are right about side effect. The purpose of reactions are automated side-effects. Data derivation should always be done with JS getters instead.
Ok, than the docs make sense as they are – thanks for clarification.
I think it should be mentioned that
observe(...)
call is side-effectful. It runs the function first time immediately (to evaluate those proxies) and the reaction is almost always a side-effect like logging, mutating, with probably the only exception of doing nothing...There's a section of Reaction scheduling but it describes another aspect (of scheduling, while the first time it's always a sync run, no matter which scheduler is applied, right?).