Postboy Help

Namespaces

A namespace is a lightweight string‑scoped group of message types. It ties the lifecycle of several subscriptions to a single scope, allowing you to clean them all up with one call.

1. Creating a namespace

Use postboy.exec(new AddNamespace(name)) on your postboy instance, then chain recordSubject(...) to register the message types that belong to this scope.
Subscriptions made to those types will be tracked by the namespace.

import {PostboyService, PostboyGenericMessage} from '@artstesh/postboy'; class ApplyFilterEvent extends PostboyGenericMessage { static readonly ID = 'filter.apply'; } class FilterChangedEvent extends PostboyGenericMessage { static readonly ID = 'filter.changed'; } export class UserFilterService { private readonly ns = 'user-filter'; constructor(private postboy: PostboyService) { this.postboy .exec(new AddNamespace(this.ns)) .recordSubject(ApplyFilterEvent) .recordSubject(FilterChangedEvent); // Subscriptions to those messages are now tracked this.postboy.sub(ApplyFilterEvent).subscribe(e => { console.log('Filter applied', e); }); } destroy(): void { this.postboy.exec(new EliminateNamespace(this.ns)); } }

2. Lifecycle

  • .exec(new AddNamespace(name)) creates the scope and returns the postboy instance for chaining.

  • recordSubject(Message) registers a message type under the active namespace.

  • sub(Message).subscribe(...) creates a subscription that the namespace tracks.

  • .exec(new EliminateNamespace(name)) unsubscribes all subscriptions registered under that namespace in one step.

After .exec(new EliminateNamespace(...)) the message types are not known to the bus, and their subscriptions are gone. You can re‑register them later if needed.

3. Namespaces vs Full Registrators

Feature

Namespace

Registrator

Boilerplate

Minimal

Requires a dedicated class

Best for

A few messages inside one class

Large message groups across a module

Cleanup

EliminateNamespace()

down()

Centralised control

No — each class manages its own

Yes — one class per feature

Use a namespace when the scope is local to a single component or service and you want automatic cleanup without creating a full registrator.

4. Important tips

  • Unique names — Use a unique string per scope. If multiple instances of the same service exist, append an instance ID (e.g., 'user-filter-' + uniqueId()).

  • Always eliminate — Call .exec(new EliminateNamespace()) in the destructor of the owning object (e.g., onDestroy, componentWillUnmount, or a custom destroy() method). Missing this call leaks subscriptions.

  • One namespace per message registration — A message type can be recorded under different namespaces, but the subscriptions from each namespace are cleaned independently.

5. Summary

Namespaces give you a simple, code‑local mechanism to group messages and auto‑clean their subscriptions. They are the recommended middle ground between raw manual control and full registrator classes.

07 мая 2026