batched
Batched functions enable you to make multiple state changes without triggering observer effects too frequently. batched
takes in a function and returns a function with an identical signature to the passed function. Under the hood a batched function will create a new transaction that will be commited at the end of the functions execution and will be rolled back if the passed function throws an error.
Basic
Before we use batched, let's look at an example that doesn't use batched udpates. Notice how the observer effect runs twice when we call incrementAll
.
This is likely not the behavior we intend, but by batching incrementAll
we can ensure that observer effect will run only once at the end of the batched function's execution.
Rollbacks
If the batched function throws an error, the state changes will not be committed, and the observer effect will not run.
Gets and Sets
Every time a batched function is executed, a new transaction is created. When we call get
or set
methods on an observable while a batched call is pending, we will be getting and setting the value associated with the pending transaction and this value will not be finalized until the transaction is commited at the end of the batched call.