Skip to main content

last

last turns an event into a value: the most recent payload from any signal with subscribe, undefined before the first.

Import​

import { last } from '@bedrock-core/observable';
import type { Last } from '@bedrock-core/observable';

Signature​

last<E, O = never>(source: Signal<E> | NativeSignal<E, O>, options?: ObservableOptions<E | undefined> & { on?: O }): Last<E>

Parameters​

ParameterTypeDefaultDescription
source *Signal<E> | NativeSignal<E, O>—Standard cleanup-return signal or native callback-removal source
options.onO—Forwarded to a native source's subscribe as its second argument
options.equalsEquals<E | undefined>Object.isWhat counts as a new payload
options.labelstring—Named in the log when a listener throws

Returns​

interface Last<E> extends ReadonlyObservable<E | undefined> {
dispose(): void; // stop following the signal; the last value stays readable
}

Usage​

import { world } from '@minecraft/server';

const spawn = last(world.afterEvents.playerSpawn);

spawn.get(); // undefined until someone spawns
spawn.subscribe(event => console.warn(event?.player.name));

const lastName = computed(() => spawn.get()?.player.name, [spawn]);

spawn.dispose(); // releases the engine subscription

Examples​

A filtered engine event​

const hurt = last(world.afterEvents.entityHurt, { on: { entityTypes: ['minecraft:player'] } });

A peer's event as a value​

import { purchase } from '@studio/economy';

const lastPurchase = last(purchase);

effect(() => hud.setLastSale(lastPurchase.get()), [lastPurchase]);

Notes​

  • Eager. The subscription is taken when last is called, so nothing is missed between creation and the first read; dispose() ends it.
  • Both signal contracts work. Sources with unsubscribe are adapted through toSignal, which preserves the returned callback token. Standard Signal sources supply their cleanup directly. dispose() is idempotent.
  • Delivery stays in the source's execution context. The adapter does not defer native before-event callbacks out of their restricted execution mode. Payloads and native handles are retained by reference, not copied; validate retained handles before later use.
  • A payload equal to the previous one — by Object.is unless equals says otherwise — notifies nobody. Use a direct Signal subscription when repeated identical payloads must count as separate occurrences.