$120 tested Claude codes · real before/after data · Full tier $15 one-timebuy --sheet=15 →
$Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. download --free →
clskills.sh — terminal v2.4 — 2,347 skills indexed● online
[CL]Skills_
ArchitectureintermediateNew

Observer Pattern

Share

Implement Observer/PubSub pattern

Works with OpenClaude

You are an architecture specialist implementing the Observer/PubSub pattern. The user wants to create a reusable event-driven system where objects (subscribers) automatically react to state changes in a subject without tight coupling.

What to check first

  • Determine if you need one-to-many (Observer) or many-to-many (PubSub) messaging
  • Decide between synchronous callbacks or asynchronous event handling
  • Check if you need typed events (TypeScript) or dynamic subscription keys

Steps

  1. Create a Subject/Emitter class with subscribe(), unsubscribe(), and notify() methods
  2. Define an Observer interface or callback signature that receives the updated state
  3. Store subscribers in a Set or Map keyed by event type to prevent duplicates and enable fast lookup
  4. Implement notify() to iterate over subscribers and call their callback with the current state
  5. Add error handling to prevent one subscriber's exception from breaking others
  6. Implement unsubscribe() to remove specific observers by reference or event type
  7. Add an optional once() method for single-execution subscriptions
  8. Test with multiple subscribers responding to the same event emission

Code

// Observer Pattern Implementation with TypeScript

type Listener<T> = (data: T) => void;
type EventMap = Record<string, any>;

class EventEmitter<Events extends EventMap> {
  private listeners: Map<keyof Events, Set<Listener<any>>> = new Map();
  private onceListeners: Map<keyof Events, Set<Listener<any>>> = new Map();

  subscribe<K extends keyof Events>(
    event: K,
    listener: Listener<Events[K]>
  ): () => void {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, new Set());
    }
    this.listeners.get(event)!.add(listener);

    // Return unsubscribe function
    return () => this.unsubscribe(event, listener);
  }

  once<K extends keyof Events>(
    event: K,
    listener: Listener<Events[K]>
  ): () => void {
    if (!this.onceListeners.has(event)) {
      this.onceListeners.set(event, new Set());
    }
    this.onceListeners.get(event)!.add(listener);

    return () => {
      this.onceListeners.get(event)?.delete(listener);
    };
  }

  emit<K extends keyof Events>(event: K, data: Events[K]): void {
    // Execute regular subscribers
    const listeners = this.listeners.get(event);
    if (listeners) {
      listeners.forEach((listener) => {
        try {
          listener(data);
        } catch (error) {
          console.error(`Error in listener for event "${String(event)}":`, error);
        }
      });

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

CategoryArchitecture
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
architectureobserverpubsub

Install command:

curl -o ~/.claude/skills/observer-pattern.md https://claude-skills-hub.vercel.app/skills/architecture/observer-pattern.md

Related Architecture Skills

Other Claude Code skills in the same category — free to download.

Want a Architecture skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.