Sharing data between addons
Expose owned operations and data through a public addon API.
Choose the public contract
| Importing addon needs | Export | Behavior |
|---|---|---|
| Read the current value frequently | ReadonlyObservable<T | undefined> | Local synchronized snapshot with get and subscribe |
| Ask a question or request a change | A Promise-returning function | Runs in the owner and returns an answer or error |
| React to an occurrence | Signal<T> | Delivers future payloads to subscribers without retaining or replaying them |
These are the existing contracts from @bedrock-core/observable. A public value can be undefined until its provider and snapshot are available. Only the owner keeps the writable observable or signal emitter.
Publish values and signals
import { observable, signal } from '@bedrock-core/observable';
import type { ReadonlyObservable, Signal } from '@bedrock-core/observable';
const currentCurrency = observable<string | undefined>('gold');
const purchases = signal<{ playerId: string; gold: number }>();
export const currency: ReadonlyObservable<string | undefined> = currentCurrency;
export const purchase: Signal<{ playerId: string; gold: number }> = purchases;
The provider updates currentCurrency.set(...) and calls purchases.emit(...). The importing addon receives the read-only contracts through its normal imports. Repeated identical signal payloads remain separate occurrences; signals do not retain a current value.
Keep storage and authority with the owner
A db collection or config accessor is local to its addon. Export an observable view when other addons need its current value; export a function when a request needs input validation or authorization.
export async function deductGold(
playerId: string, gold: number, actorId?: string,
): Promise<void> {
authorize({ entity: playerId }, actorId, 'write');
const document = balances.for(playerOf(playerId));
document.patch({ gold: (document.get()?.gold ?? 0) - gold });
purchases.emit({ playerId, gold });
}
Map persisted documents onto observables in the provider. Persistence and exposure are separate decisions: exporting a function or signal does not make the underlying collection accessible.
Consume the API
import { currency, purchase, deductGold } from '@studio/economy';
const stopCurrency = currency.subscribe(updateCurrency);
const stopPurchase = purchase.subscribe(({ playerId, gold }) => {
hud.flash(playerId, `-${gold}`);
});
await deductGold(player.id, 5, player.id);
Keep the unsubscribe functions for the consuming feature's lifetime. The runtime also releases subscriptions when the consumer stops. Use last when a screen needs a signal's most recent payload as an observable value.
Next steps
- Public addon APIs — exports, imports, availability and errors
- Observable values — local mutable state and read-only views
- Signals — transient occurrences and subscription cleanup
- Authorization — validate operations on behalf of players