Often multiple changes can be made to the store quickly, but we would like reaction to be called only once.
Let's consider such example:
We're changing store state 3 times in a row and we might want to decide if reaction should be called each time or if it should be called only once after all operations are finished.
In Statek, this is called scheduling.
There are 2 built-in schedulers:
- async scheduler (default) - will collect all updates and run reaction on the next 'tick'.
- sync scheduler - will call reaction instantly
It is also possible to use custom scheduler.
By default, async scheduler is used
Again, if running such code:
Output in the console would be
This is because first call is always executed instantly, while other would be scheduled using scheduler (and
async scheduler is the default one).
Setting reaction scheduler
To change scheduler, we can use 2nd parameter of
watch function which allows us to provide various options.
In above example, if we'll run
Console would output
All other options avaliable are listed in API reference section
The same option is avaliable in
In example above, where we call
We could want to group those 3 operations together, while avoiding having to wait for the next tick, which is the case with async scheduler.
To do that, we can call such operations like:
Such call will collect all operations happening inside before flushing them and allowing any reaction to pick them.
Other batching & scheduling functions
Will force sync scheduler for operations happening during the call.
sync are batched. Flush will not happen until the end of the call
Will flush after every single operation inside the call.
syncEvery is called inside
sync - it will still flush after every operation.
Will not register any read operations during the call
In example above, only
.count read operation will be recorded. Therefore if we'll call
Reaction will be called again, but if we call
Reaction will not be called.