Helper Functions

mergeIntoObservable

If you want to mergeIntoObservable a deep object into an observable, mergeIntoObservable can do that and retain all of the existing observables and listeners on the way, and fire listeners as values change. This is used by persistObservable under the hood.

import { mergeIntoObservable } from '@legendapp/state'

const obs = observable({ store: { text: 'hello', other: 'hello there' } })

obs.store.text.on('change', () => ... )

const newValue = { store: { text: 'hi', other: 'hi there' }}
mergeIntoObservable(obs, newValue)

// Change handler on obs.store.text is called

obs.store === newValue.store // ✅ true

lockObservable

To ensure that observables are only modified within certain actions, you can lock observables so that they cannot be modified, then unlock them temporarily in your actions. This is used under the hood by computed.

import { lockObservable } from '@legendapp/state'

const obs = observable({ state: { ... } })
lockObservable(obs, true);

function safeAction() {
    // Unlock it to modify it
    lockObservable(obs, false)
    // Modify it
    obs.set({ state: { ... } })
    // Lock it back
    lockObservable(obs, true)
}