blac

    Core

    subscribe and consume

    The lowest-level ways to observe a bloc — subscribe to every change, or consume a set of paths and be woken only when one of them changes. For plugins, devtools, and infrastructure.

    The lowest-level ways to observe a bloc. Every container inherits two methods from StructuralContainer (the structural layer under every Cubit):

    • subscribe(cb) — run cb after every change.
    • consume(cb) — register a path-scoped consumer. It watches nothing until you call setPaths, then cb runs only when one of those paths changed value.

    Almost no application code needs these. They exist for plugins, devtools, and infrastructure that must compose observation directly on a container. If you are inside a React component, use useBloc; if you are outside React, use watch. watch is itself a thin wrapper around container.subscribe(...).

    Stability

    ALL_PATHS and the PathSet type are public — @blac/core re-exports ALL_PATHS (value) and PathSet (type). The PathInterner and its numeric PathIds are reachable through container.interner, but the representation of ids can change between releases. Treat them as opaque: intern a path string through the container’s own interner and pass the result back, rather than storing or comparing ids across classes.

    Signatures

    subscribe(cb: (dirty: PathSet) => void): () => void
    consume(cb: (dirty: PathSet) => void): Consumer
    flush(): void
    interface Consumer {
    readonly paths: PathSet;
    setPaths(paths: PathSet): void;
    dispose(): void;
    }
    MemberDescription
    subscribe(cb)Listens to every change. Returns an unsubscribe function. Equivalent to consume(cb) followed by setPaths(ALL_PATHS).
    consume(cb)Registers a consumer that watches nothing until setPaths is called.
    consumer.setPaths(p)Replaces the watched paths. Pass a Set<PathId> for specific fields, or ALL_PATHS for every change. Can be called again whenever the paths change.
    consumer.dispose()Removes the consumer.
    flush()Delivers pending changes now instead of waiting for the microtask.
    consumers()The live consumers (subscribe listeners included), for inspection and devtools. consumerCount is their number.

    The PathSet shape

    const ALL_PATHS: unique symbol;
    type AllPaths = typeof ALL_PATHS;
    type PathSet = Set<PathId> | AllPaths;
    type PathId = number;

    A PathSet is either the ALL_PATHS sentinel (“every change”) or a Set<PathId> of interned path ids. You get ids from the container’s interner: bloc.interner.intern('user.name').

    The dirty value passed to your callback is always a Set<PathId> — never ALL_PATHS. It holds the changed ids among the paths any consumer on the container watches. When no watched path changed (for example, an ALL_PATHS subscriber woken by a change nobody reads), it holds only the root id, for which interner.lookup(id) === ''.

    The callback contract

    • Coalesced, asynchronous. The container uses a microtask scheduler by default, so several synchronous emit/patch/update calls fold into a single flush. Your callback fires once per flush, after the current tick. See System Events for the batching model.
    • Path-scoped. A consume callback runs only when one of its watched paths changed value. The new state is already applied when it runs — read container.state inside the callback.
    • No immediate fire. Unlike watch, neither method invokes the callback on setup. If you need the current value immediately, read container.state yourself.
    • No work without consumers. With no consumers, a mutation only replaces the state — no diff, no flush.
    • patch is emit of a merge. patch(p) is exactly emit(deepMerge(state, p)), so both go through the same diff against the watched paths. Unchanged references are pruned: a patch that replaces an array with equal contents wakes readers of the whole array, but not readers of unchanged children.
    • Errors are collected, not swallowed silently. A throw from your callback is recorded; after all consumers run, a single error re-throws as-is, and multiple throw as an AggregateError.

    Unsubscribe and dispose

    subscribe returns an unsubscribe function; consume returns a Consumer whose dispose() does the same job. Forgetting to call either leaks the consumer for the life of the bloc.

    import {
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    } from '@blac/core';
    import {
    function ensure<T extends StateContainerConstructor>(BlocClass: T, opts?: {
    args?: ExtractArgs<T>;
    }): InstanceType<T>

    Ensure an instance exists without taking ownership (no ref added). Instance identity is derived purely from args, matching acquire.

    ensure
    } from '@blac/core';
    class
    class CounterCubit
    CounterCubit
    extends
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    <{
    count: number
    count
    : number }> {
    constructor() {
    super({
    count: number
    count
    : 0 });
    }
    CounterCubit.increment(): void
    increment
    () {
    this.
    Cubit<{ count: number; }, void, Record<string, never>>.patch(partial: {
    count?: number | undefined;
    }): void

    Merge partial into the state. Plain-object branches merge recursively; arrays, class instances, Map, Set, Date and primitives replace the slot. A key cannot be removed this way (undefined is stored as a value); use emit or update for that.

    @see ― emit for the StateContainer concerns layered onto super.patch.

    patch
    ({
    count?: number | undefined
    count
    : this.
    StateContainer<{ count: number; }, void, Record<string, never>>.state: {
    count: number;
    }
    state
    .
    count: number
    count
    + 1 });
    }
    }
    const
    const counter: CounterCubit
    counter
    =
    ensure<typeof CounterCubit>(BlocClass: typeof CounterCubit, opts?: {
    args?: void | undefined;
    } | undefined): CounterCubit

    Ensure an instance exists without taking ownership (no ref added). Instance identity is derived purely from args, matching acquire.

    ensure
    (
    class CounterCubit
    CounterCubit
    );
    // Every change.
    const
    const unsubscribe: () => void
    unsubscribe
    =
    const counter: CounterCubit
    counter
    .
    StructuralContainer<{ count: number; }>.subscribe(cb: (dirty: PathSet) => void): () => void

    Listen to every change. Returns the unsubscribe function.

    subscribe
    ((
    dirty: PathSet
    dirty
    ) => {
    // `dirty` is the changed PathSet; the new state is already applied.
    var console: Console
    console
    .
    Console.log(...data: any[]): void

    The console.log() static method outputs a message to the console.

    MDN Reference

    log
    ('counter changed ->',
    const counter: CounterCubit
    counter
    .
    StateContainer<{ count: number; }, void, Record<string, never>>.state: {
    count: number;
    }
    state
    .
    count: number
    count
    );
    });
    const counter: CounterCubit
    counter
    .
    CounterCubit.increment(): void
    increment
    ();
    const counter: CounterCubit
    counter
    .
    CounterCubit.increment(): void
    increment
    (); // both fold into ONE coalesced flush next microtask
    const unsubscribe: () => void
    unsubscribe
    ();

    Path-scoped consumer

    import {
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    ,
    function ensure<T extends StateContainerConstructor>(BlocClass: T, opts?: {
    args?: ExtractArgs<T>;
    }): InstanceType<T>

    Ensure an instance exists without taking ownership (no ref added). Instance identity is derived purely from args, matching acquire.

    ensure
    } from '@blac/core';
    class
    class UserCubit
    UserCubit
    extends
    class Cubit<S extends object = any, Args = void, Deps extends object = Record<string, never>>

    Cubit<S> is a StateContainer<S> that exposes mutation publicly.

    That is the whole difference, and it is a real one: on StateContainer emit / patch / update are protected, so a container mutates itself from its own methods and callers go through the API it chooses to publish. Cubit re-declares the three as public for the cases where a caller legitimately drives state from outside — test helpers, devtools time-travel, benchmarks.

    Reach for StateContainer when business logic should live in the class, and Cubit when the caller owns the transitions.

    Cubit
    <{
    user: {
    name: string;
    email: string;
    }
    user
    : {
    name: string
    name
    : string;
    email: string
    email
    : string } }> {
    constructor() {
    super({
    user: {
    name: string;
    email: string;
    }
    user
    : {
    name: string
    name
    : 'Ada',
    email: string
    email
    : 'ada@x.io' } });
    }
    UserCubit.rename(name: string): void
    rename
    (
    name: string
    name
    : string) {
    this.
    Cubit<{ user: { name: string; email: string; }; }, void, Record<string, never>>.patch(partial: {
    user?: {
    name?: string | undefined;
    email?: string | undefined;
    } | undefined;
    }): void

    Merge partial into the state. Plain-object branches merge recursively; arrays, class instances, Map, Set, Date and primitives replace the slot. A key cannot be removed this way (undefined is stored as a value); use emit or update for that.

    @see ― emit for the StateContainer concerns layered onto super.patch.

    patch
    ({
    user?: {
    name?: string | undefined;
    email?: string | undefined;
    } | undefined
    user
    : {
    name?: string | undefined
    name
    } });
    }
    }
    const
    const user: UserCubit
    user
    =
    ensure<typeof UserCubit>(BlocClass: typeof UserCubit, opts?: {
    args?: void | undefined;
    } | undefined): UserCubit

    Ensure an instance exists without taking ownership (no ref added). Instance identity is derived purely from args, matching acquire.

    ensure
    (
    class UserCubit
    UserCubit
    );
    const
    const consumer: Consumer
    consumer
    =
    const user: UserCubit
    user
    .
    StructuralContainer<{ user: { name: string; email: string; }; }>.consume(cb: (dirty: PathSet) => void): Consumer

    Register a reader. It watches nothing until setPaths is called; after that cb runs, once per flush, when a watched path changed value. cb receives the changed path ids among those any consumer watches.

    consume
    (() => {
    var console: Console
    console
    .
    Console.log(...data: any[]): void

    The console.log() static method outputs a message to the console.

    MDN Reference

    log
    ('name ->',
    const user: UserCubit
    user
    .
    StateContainer<{ user: { name: string; email: string; }; }, void, Record<string, never>>.state: {
    user: {
    name: string;
    email: string;
    };
    }
    state
    .
    user: {
    name: string;
    email: string;
    }
    user
    .
    name: string
    name
    );
    });
    const consumer: Consumer
    consumer
    .
    Consumer.setPaths(paths: PathSet): void

    Replace the watched paths. The set is indexed as passed and must not be mutated afterwards; passing the current set again is a no-op. ALL_PATHS wakes on every change.

    setPaths
    (new
    var Set: SetConstructor
    new <number>(iterable?: Iterable<number> | null | undefined) => Set<number> (+1 overload)
    Set
    ([
    const user: UserCubit
    user
    .
    StructuralContainer<{ user: { name: string; email: string; }; }>.interner: PathInterner
    interner
    .
    PathInterner.intern(path: string): PathId
    intern
    ('user.name')]));
    const user: UserCubit
    user
    .
    UserCubit.rename(name: string): void
    rename
    ('Grace'); // wakes the consumer
    const user: UserCubit
    user
    .
    Cubit<{ user: { name: string; email: string; }; }, void, Record<string, never>>.patch(partial: {
    user?: {
    name?: string | undefined;
    email?: string | undefined;
    } | undefined;
    }): void

    Merge partial into the state. Plain-object branches merge recursively; arrays, class instances, Map, Set, Date and primitives replace the slot. A key cannot be removed this way (undefined is stored as a value); use emit or update for that.

    @see ― emit for the StateContainer concerns layered onto super.patch.

    patch
    ({
    user?: {
    name?: string | undefined;
    email?: string | undefined;
    } | undefined
    user
    : {
    email?: string | undefined
    email
    : 'g@x.io' } }); // does not
    const consumer: Consumer
    consumer
    .
    Consumer.dispose(): void

    Stop watching. Idempotent.

    dispose
    ();

    Inside React vs outside React

    subscribe and consume are the floor of a three-tier API. Pick the highest tier that fits:

    Where you areUseWhat you get
    Inside a React componentuseBlocAuto-tracked, path-scoped re-renders; lifecycle tied to mount.
    Outside React (logging, sync, imperative UI, tests)watchThe bloc instance, fires once immediately, multi-bloc, watch.STOP.
    Building a plugin / devtools / infrasubscribe / consumeRaw PathSet deltas, no instance sugar, no immediate fire.

    In short: inside React → useBloc; outside React → watch for almost everything, and subscribe / consume only when you are composing on the container itself. watch is container.subscribe(...) plus instance resolution, an immediate fire, and a STOP sentinel.

    See also

    • watch — the outside-React wrapper around subscribe; prefer it unless you need raw container access
    • Tracking — how useBloc records the paths a render reads and passes them to setPaths
    • System Events — the microtask flush and coalescing model behind every callback
    • DirtyTalk — the underlying channel and the Space/Scheduler model it is built on