Skip to main content

Waiting For State Change

Waiting is an observation strategy that utilizes .watch under the hood. It allows us to watch for state value changes until it matches a certain value or fulfils a certain condition then stops watching and returns a snapshot of that state.

Consider the code below, there are two things that we can do with it.

const CounterState = new StateManager(0)

setInterval(() => {
const randomNumber = Math.round(Math.random() * 100)
CounterState.set(randomNumber)
}, 1000)

Waiting for a specific value

We can pass a value to .wait and it will resolve when the state matches that value. The state is compared with the expected value using Object.is.

In this example, the promise will resolve when the state equals to 42.

await CounterState.wait(42)

tip

The .isInitializing property of StateManager and AsyncStateManager can be used in a similar way to wait for initialization to complete (Example: ExampleState.isInitializing.wait(false)).

Waiting for a condition to be fulfilled

We can also pass a callback to .wait to fine tune the waiting behavior. The state snapshot will be passed to the function each time the state changes and the callback should return either true or false.

In this example, the promise will resolve when the state is a number that is divisible by 5.

await CounterState.wait(state => state % 5 === 0)

tip

When the condition is fulfilled, the .wait method returns a Promise that resolves into a snapshot of the state that fulfilled the condition. This is useful when we only know what condition to expect but not a specific value, as we could capture the value right after waiting.