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



