alepha@docs:~/framework/docs/reference/primitives$
cat $topic.md | pretty
1 min read

#$topic

#Import

typescript
1import { $topic } from "alepha/topic";

#Overview

Creates a topic primitive for publish/subscribe messaging and event-driven architecture.

Enables decoupled communication through a pub/sub pattern where publishers send messages and multiple subscribers receive them. Supports type-safe messages, real-time delivery, event filtering, and pluggable backends (memory, Redis, custom providers).

Use Cases: User notifications, real-time chat, event broadcasting, microservice communication

#Options

Option Type Required Description
name string No Unique name identifier for the topic
description string No Human-readable description of the topic's purpose and usage
provider "memory" | Service<TopicProvider> No Topic provider configuration for message storage and delivery
schema T Yes Zod schema defining the structure of messages published to this topic
handler TopicHandler<T> No Default subscriber handler function that processes messages published to this topic
retain boolean No Whether the last published message should be retained and delivered to new subscribers

#Examples

ts
 1class NotificationService { 2  dateTime = $inject(DateTimeProvider); 3  4  userActivity = $topic({ 5    name: "user-activity", 6    schema: { 7      payload: z.object({ 8        userId: z.text(), 9        action: z.enum(["login", "logout", "purchase"]),10        timestamp: z.number(),11      }),12    },13    handler: async (message) => {14      console.log(`User ${message.payload.userId}: ${message.payload.action}`);15    },16  });17 18  async trackLogin(userId: string) {19    await this.userActivity.publish({20      userId,21      action: "login",22      timestamp: this.dateTime.nowMillis(),23    });24  }25 26  async subscribeToEvents() {27    await this.userActivity.subscribe(async (message) => {28      // Additional subscriber logic29    });30  }31}