Quick Start: Publish and Subscribe
The simplest way to use Postboy for one‑way messaging is with PostboyGenericMessage.
It works exactly like a callback message except there is no return value — the publisher fires the message and every subscriber reacts independently.
1. Define the message
Create a class that extends PostboyGenericMessage. The ID property is a convention for debugging and tracing.
import {PostboyGenericMessage} from '@artstesh/postboy';
export class StockUpdatedEvent extends PostboyGenericMessage {
static readonly ID = 'stock.updated';
constructor(public readonly productId: string, public readonly newStatus: string) {
super();
}
}
2. Register the message type
Inside a service, register the message with ConnectMessage and exec.
Then subscribe and define the reaction.
import {AppPostboyService} from '@shared/services/app-postboy.service';
import {ConnectMessage} from '@artstesh/postboy';
import {Subject} from 'rxjs';
import {StockUpdatedEvent} from './messages/events/stock-updated.event';
export class InventoryService {
constructor(private postboy: AppPostboyService) {
// Step 1: connect the message type
this.postboy.exec(new ConnectMessage(StockUpdatedEvent, new Subject<StockUpdatedEvent>()));
// Step 2: subscribe and react
this.postboy.sub(StockUpdatedEvent).subscribe((msg) => {
console.log(`Stock changed for ${msg.productId}: ${msg.newStatus}`);
// update internal state, refresh UI bindings, etc.
});
}
}
3. Fire the message from anywhere
Any component or service can publish the event with fire.
The publisher has no knowledge of who listens.
import {AppPostboyService} from '@shared/services/app-postboy.service';
import {StockUpdatedEvent} from './messages/events/stock-updated.event';
export class StockSimulatorComponent {
constructor(private postboy: AppPostboyService) {
}
simulateChange(): void {
// Fire the event
this.postboy.fire(new StockUpdatedEvent('P-42', 'Out of Stock'));
}
}
4. Multiple subscribers
Any number of components or services can subscribe to the same message.
They remain completely independent of each other and of the publisher.
// In a header component
this.postboy.sub(StockUpdatedEvent).subscribe((msg) => {
this.updateBadge(msg.productId);
});
// In a toast notification service
this.postboy.sub(StockUpdatedEvent).subscribe((msg) => {
this.showToast(`Product ${msg.productId} is now ${msg.newStatus}`);
});
Key points
PostboyGenericMessage represents a fire‑and‑forget event.
Registration is identical to callback messages: ConnectMessage + exec + sub.
Publishing is done with fire; subscribers react but do not return a value.
The publisher and subscribers are fully decoupled — you can add or remove subscribers without changing the source.
03 мая 2026