effect
effect runs a function now and again whenever one of its listed dependencies changes.
Import
import { effect } from '@bedrock-core/observable';
Signature
effect(run: () => void, deps: readonly ReadonlyObservable<unknown>[], options?: { label?: string }): Unsubscribe
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
run * | () => void | — | The side effect; runs once now, then on every dependency change |
deps * | readonly ReadonlyObservable<unknown>[] | — | What it reacts to — anything with get and subscribe |
options.label | string | 'effect' | Named in the log when run throws |
Returns
An Unsubscribe that stops the effect. It does not run run again.
Usage
const phase = observable<'lobby' | 'fight' | 'end'>('lobby');
const stop = effect(() => {
bossBar.setTitle(phase.get()); // runs now with 'lobby', then on every change
}, [phase]);
stop();
Examples
Keeping engine state in step with a value
effect(() => {
world.gameRules.pvp = config.server.pvp.get();
}, [config.server.pvp]);
Several dependencies
effect(() => {
hud.render(shared.event.get(), aliveCount.get());
}, [shared.event, aliveCount]);
Notes
- Dependencies are listed, not tracked. A read inside
runof an observable not indepsdoes not re-run the effect. - A
runthat throws is reported underlabel; the effect stays subscribed. - Inside a
batch, an effect whose dependencies both changed runs exactly once, at the end. effectiscomputedwithout a value: the same scheduling, no result.