liveBook · Manning

Observer pattern

As explained in Idiomatic Rust

The observer pattern is a behavioral design pattern in which a subject notifies registered observers about events without depending on their concrete implementations.

The observer pattern lets a subject notify registered observers about events without depending on their concrete implementations. It suits event processing and handling, including networked services, and provides looser coupling than callbacks. section 5.5 section 5.5.1

In Rust, separate the roles with Observer and Observable traits. A subject can store observers as weak pointers, allowing shared ownership without keeping observers alive; attach and detach manage registrations, while update notifies live observers. section 5.5.2

Listing 5.11 Implementing Observable for Subject
pub struct Subject {
    observers: Vec<Weak<dyn Observer<Subject = Self>>>,    #1
}

impl Observable for Subject {
    type Observer = Arc<dyn Observer<Subject = Self>>;  #2
    fn update(&self) {
        self.observers
            .iter()
            .flat_map(|o| o.upgrade())      #3
            .for_each(|o| o.observe(self));          #4
    }
    fn attach(&mut self, observer: Self::Observer) {
        self.observers.push(Arc::downgrade(&observer));     #5
    }
    fn detach(&mut self, observer: Self::Observer) {
        self.observers
            .retain(|f| {
              !f.ptr_eq(&Arc::downgrade(&observer))   #6
            });
    }
}

See a subject implementation using Weak references, Arc-based registration, and update-time notification. section 5.5.2

A subject with state

A subject holding a string state can notify two registered observers; each prints that state alongside its own name. Callbacks may suffice for simple cases, while observers help when registrations and many-to-one notification are useful. section 5.5.2 section 5.8

How Idiomatic Rust covers it

How deep it goes
Defines observer and observable traits, then implements registration, removal, and notification with shared and weak pointers.
Examples
Demonstrates a string-state subject notifying two named observers that print the observed state.
What it assumes
Builds on generics, traits, pattern matching, and closures rather than introducing those foundations from zero.
What you can do after
Build a Rust observer implementation with traits, registration methods, and weak references.
How it connects
Contrasts observers with callbacks and connects the implementation to traits, closures, and shared ownership.

Also explained in

Compare how 4 books explain observer pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.