nx-js / observer-util

Transparent reactivity with 100% language coverage. Made with ❤️ and ES6 Proxies.
MIT License
1.2k stars 94 forks source link

Documentation suggestion #33

Closed ivan-kleshnin closed 5 years ago

ivan-kleshnin commented 5 years ago

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...

import { observable, observe } from '@nx-js/observer-util';

const counter = observable({ num: 0 });

+ // this calls countLogger and logs 0
const countLogger = observe(() => console.log(counter.num));

// this calls countLogger and logs 1
counter.num++;

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?).

solkimicreb commented 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.

ivan-kleshnin commented 5 years ago

Ok, than the docs make sense as they are – thanks for clarification.