Programming Search⌘K

Patternadvanced

Event Aggregator

Also called event aggregator pattern, EventAggregator.

An event aggregator is a single source of events for many objects. It registers for the events of the source objects, and clients register only with it.

Family
behavioral-design
Intent
Channel events from multiple objects into a single object to simplify registration for clients.

Intent

Channel events from multiple objects into a single object to simplify registration for clients.1

Problem

A system with lots of objects can lead to complexities when a client wants to subscribe to events. The client has to find and register for each object individually. If each object has multiple events, then each event requires a separate subscription.1

Solution

An Event Aggregator acts as a single source of events for many objects. It registers for all the events of the many objects, and clients register with just the aggregator.1 It is a simple element of indirection. When an event comes from a source object, the aggregator propagates that event to the target objects.1

   consultant A --\                       /--> screen
   consultant B ----> EventAggregator ---+
   consultant C --/   (registers once      \--> phone
                       with each source)
         sources                             clients register only here

An aggregator can also generalize the event. It converts events that are specific to a source object into a more generic event, so the observers need to register for fewer individual event types.1

Example

Fowler's example tracks the consultants of a company. When a consultant moves, the consultant object signals one event for the change of location, and one more event if the availability changes.1 The aggregator listens to all consultants. For each incoming event it signals two events: a specific one for the type of change, and a general one that only says that a change occurred. Clients can then register to the granularity they wish.1

In the example files, a screen registers for the general event and a phone registers for the specific availability event. Neither of them knows the consultants. Alice is not available at home, so her move away from home also changes her availability. The program prints:

alice moves to Leeds
screen: alice changed
phone: availability of alice changed
screen: alice changed
bob moves to Paris
screen: bob changed
PythonGitHub
class Consultant:
    def __init__(self, name, home, available_at_home, location):
        self.name, self.home = name, home
        self.available_at_home, self.location = available_at_home, location
        self.location_changed, self.availability_changed = [], []

    def available_at(self, place):
        return self.available_at_home if place == self.home else True

    def move(self, place):
        print(f"{self.name} moves to {place}")
        if self.location != place:
            for h in self.location_changed:
                h(self)
            if self.available_at(place) != self.available_at(self.location):
                for h in self.availability_changed:
                    h(self)
            self.location = place


class EventAggregator:
    def __init__(self):
        self.changed, self.location, self.availability = [], [], []

    def listen(self, consultant):
        consultant.location_changed.append(lambda c: self._signal(self.location, c))
        consultant.availability_changed.append(lambda c: self._signal(self.availability, c))

    def _signal(self, specific, c):
        for h in specific:  # the specific event
            h(c)
        for h in self.changed:  # and the general one
            h(c)


agg = EventAggregator()
alice = Consultant("alice", "London", False, "London")
bob = Consultant("bob", "Paris", True, "Lyon")
for c in (alice, bob):
    agg.listen(c)

agg.changed.append(lambda c: print(f"screen: {c.name} changed"))
agg.availability.append(lambda c: print(f"phone: availability of {c.name} changed"))

alice.move("Leeds")
bob.move("Paris")
Output
alice moves to Leeds
screen: alice changed
phone: availability of alice changed
screen: alice changed
bob moves to Paris
screen: bob changed
  • Verdict: idiom. Lists of functions are the events.
#include <functional>
#include <iostream>
#include <string>
#include <vector>

struct Consultant;
using Handler = std::function<void(const Consultant&)>;

struct Signal {
    std::vector<Handler> handlers;
    void add(Handler h) { handlers.push_back(std::move(h)); }
    void fire(const Consultant& c) const { for (const auto& h : handlers) h(c); }
};

struct Consultant {
    std::string name, home;
    bool availableAtHome;
    std::string location;
    Signal locationChanged, availabilityChanged;

    bool availableAt(const std::string& place) const { return place == home ? availableAtHome : true; }

    void move(const std::string& place) {
        std::cout << name << " moves to " << place << "\n";
        if (location != place) {
            locationChanged.fire(*this);
            if (availableAt(place) != availableAt(location)) availabilityChanged.fire(*this);
            location = place;
        }
    }
};

struct EventAggregator {
    Signal changed, location, availability;

    void listen(Consultant& c) {
        c.locationChanged.add([this](const Consultant& x) { signal(location, x); });
        c.availabilityChanged.add([this](const Consultant& x) { signal(availability, x); });
    }
    void signal(const Signal& specific, const Consultant& c) const {
        specific.fire(c);  // the specific event
        changed.fire(c);   // and the general one
    }
};

int main() {
    EventAggregator agg;
    Consultant alice{"alice", "London", false, "London", {}, {}};
    Consultant bob{"bob", "Paris", true, "Lyon", {}, {}};
    agg.listen(alice);
    agg.listen(bob);

    agg.changed.add([](const Consultant& c) { std::cout << "screen: " << c.name << " changed\n"; });
    agg.availability.add([](const Consultant& c) { std::cout << "phone: availability of " << c.name << " changed\n"; });

    alice.move("Leeds");
    bob.move("Paris");
}
Output
alice moves to Leeds
screen: alice changed
phone: availability of alice changed
screen: alice changed
bob moves to Paris
screen: bob changed
  • Verdict: idiom. Vectors of std::function values are the events. The aggregator must live longer than the consultants that hold its lambdas.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class Main {
    static final class Signal {
        private final List<Consumer<Consultant>> handlers = new ArrayList<>();
        void add(Consumer<Consultant> h) { handlers.add(h); }
        void fire(Consultant c) { handlers.forEach(h -> h.accept(c)); }
    }

    static final class Consultant {
        final Signal locationChanged = new Signal();
        final Signal availabilityChanged = new Signal();
        final String name, home;
        final boolean availableAtHome;
        String location;

        Consultant(String name, String home, boolean availableAtHome, String location) {
            this.name = name;
            this.home = home;
            this.availableAtHome = availableAtHome;
            this.location = location;
        }

        boolean availableAt(String place) { return place.equals(home) ? availableAtHome : true; }

        void move(String place) {
            System.out.println(name + " moves to " + place);
            if (!location.equals(place)) {
                locationChanged.fire(this);
                if (availableAt(place) != availableAt(location)) availabilityChanged.fire(this);
                location = place;
            }
        }
    }

    static final class EventAggregator {
        final Signal changed = new Signal();
        final Signal location = new Signal();
        final Signal availability = new Signal();

        void listen(Consultant c) {
            c.locationChanged.add(x -> signal(location, x));
            c.availabilityChanged.add(x -> signal(availability, x));
        }

        private void signal(Signal specific, Consultant c) {
            specific.fire(c); // the specific event
            changed.fire(c); // and the general one
        }
    }

    public static void main(String[] args) {
        EventAggregator agg = new EventAggregator();
        Consultant alice = new Consultant("alice", "London", false, "London");
        Consultant bob = new Consultant("bob", "Paris", true, "Lyon");
        agg.listen(alice);
        agg.listen(bob);

        agg.changed.add(c -> System.out.println("screen: " + c.name + " changed"));
        agg.availability.add(c -> System.out.println("phone: availability of " + c.name + " changed"));

        alice.move("Leeds");
        bob.move("Paris");
    }
}
Output
alice moves to Leeds
screen: alice changed
phone: availability of alice changed
screen: alice changed
bob moves to Paris
screen: bob changed
  • Verdict: idiom. Lists of Consumer functions are the events.
using System;

var agg = new EventAggregator();
var alice = new Consultant("alice", "London", false, "London");
var bob = new Consultant("bob", "Paris", true, "Lyon");
agg.Listen(alice);
agg.Listen(bob);

agg.ConsultantChanged += c => Console.WriteLine($"screen: {c.Name} changed");
agg.ConsultantAvailabilityChanged += c => Console.WriteLine($"phone: availability of {c.Name} changed");

alice.Move("Leeds");
bob.Move("Paris");

class Consultant
{
    public event Action<Consultant>? LocationChanged;
    public event Action<Consultant>? AvailabilityChanged;
    public string Name { get; }
    private readonly string home;
    private readonly bool availableAtHome;
    private string location;

    public Consultant(string name, string home, bool availableAtHome, string location)
    {
        Name = name;
        this.home = home;
        this.availableAtHome = availableAtHome;
        this.location = location;
    }

    private bool AvailableAt(string place) => place == home ? availableAtHome : true;

    public void Move(string place)
    {
        Console.WriteLine($"{Name} moves to {place}");
        if (location != place)
        {
            LocationChanged?.Invoke(this);
            if (AvailableAt(place) != AvailableAt(location)) AvailabilityChanged?.Invoke(this);
            location = place;
        }
    }
}

class EventAggregator
{
    public event Action<Consultant>? ConsultantChanged;
    public event Action<Consultant>? ConsultantLocationChanged;
    public event Action<Consultant>? ConsultantAvailabilityChanged;

    public void Listen(Consultant subject)
    {
        subject.LocationChanged += c => { ConsultantLocationChanged?.Invoke(c); ConsultantChanged?.Invoke(c); };
        subject.AvailabilityChanged += c => { ConsultantAvailabilityChanged?.Invoke(c); ConsultantChanged?.Invoke(c); };
    }
}
Output
alice moves to Leeds
screen: alice changed
phone: availability of alice changed
screen: alice changed
bob moves to Paris
screen: bob changed
  • Verdict: idiom. C# events, with the event names of Fowler's example.
JavaScriptGitHub
const { EventEmitter } = require("node:events");

class Consultant extends EventEmitter {
  constructor(name, home, availableAtHome, location) {
    super();
    Object.assign(this, { name, home, availableAtHome, location });
  }
  availableAt(place) {
    return place === this.home ? this.availableAtHome : true;
  }
  move(place) {
    console.log(`${this.name} moves to ${place}`);
    if (this.location !== place) {
      this.emit("locationChanged", this);
      if (this.availableAt(place) !== this.availableAt(this.location)) this.emit("availabilityChanged", this);
      this.location = place;
    }
  }
}

class EventAggregator extends EventEmitter {
  listen(consultant) {
    consultant.on("locationChanged", (c) => this.signal("location", c));
    consultant.on("availabilityChanged", (c) => this.signal("availability", c));
  }
  signal(specific, c) {
    this.emit(specific, c); // the specific event
    this.emit("changed", c); // and the general one
  }
}

const agg = new EventAggregator();
const alice = new Consultant("alice", "London", false, "London");
const bob = new Consultant("bob", "Paris", true, "Lyon");
for (const c of [alice, bob]) agg.listen(c);

agg.on("changed", (c) => console.log(`screen: ${c.name} changed`));
agg.on("availability", (c) => console.log(`phone: availability of ${c.name} changed`));

alice.move("Leeds");
bob.move("Paris");
Output
alice moves to Leeds
screen: alice changed
phone: availability of alice changed
screen: alice changed
bob moves to Paris
screen: bob changed
  • Verdict: library. Node's EventEmitter gives the events; the aggregator is an emitter that listens to other emitters.
TypeScriptGitHub
type Handler = (c: Consultant) => void;

class Signal {
  private handlers: Handler[] = [];
  add(h: Handler): void { this.handlers.push(h); }
  fire(c: Consultant): void { for (const h of this.handlers) h(c); }
}

class Consultant {
  readonly locationChanged = new Signal();
  readonly availabilityChanged = new Signal();
  name: string;
  home: string;
  availableAtHome: boolean;
  location: string;
  constructor(name: string, home: string, availableAtHome: boolean, location: string) {
    this.name = name;
    this.home = home;
    this.availableAtHome = availableAtHome;
    this.location = location;
  }
  availableAt(place: string): boolean {
    return place === this.home ? this.availableAtHome : true;
  }
  move(place: string): void {
    console.log(`${this.name} moves to ${place}`);
    if (this.location !== place) {
      this.locationChanged.fire(this);
      if (this.availableAt(place) !== this.availableAt(this.location)) this.availabilityChanged.fire(this);
      this.location = place;
    }
  }
}

class EventAggregator {
  readonly changed = new Signal();
  readonly location = new Signal();
  readonly availability = new Signal();
  listen(c: Consultant): void {
    c.locationChanged.add((x) => this.signal(this.location, x));
    c.availabilityChanged.add((x) => this.signal(this.availability, x));
  }
  private signal(specific: Signal, c: Consultant): void {
    specific.fire(c); // the specific event
    this.changed.fire(c); // and the general one
  }
}

const agg = new EventAggregator();
const alice = new Consultant("alice", "London", false, "London");
const bob = new Consultant("bob", "Paris", true, "Lyon");
for (const c of [alice, bob]) agg.listen(c);

agg.changed.add((c) => console.log(`screen: ${c.name} changed`));
agg.availability.add((c) => console.log(`phone: availability of ${c.name} changed`));

alice.move("Leeds");
bob.move("Paris");
Output
alice moves to Leeds
screen: alice changed
phone: availability of alice changed
screen: alice changed
bob moves to Paris
screen: bob changed
  • Verdict: idiom. A small typed Signal class holds the handlers of one event.
package main

import "fmt"

type Handler func(c *Consultant)

type Signal []Handler

func (s *Signal) Add(h Handler) { *s = append(*s, h) }
func (s Signal) Fire(c *Consultant) {
	for _, h := range s {
		h(c)
	}
}

type Consultant struct {
	Name, Home          string
	AvailableAtHome     bool
	Location            string
	LocationChanged     Signal
	AvailabilityChanged Signal
}

func (c *Consultant) AvailableAt(place string) bool {
	if place == c.Home {
		return c.AvailableAtHome
	}
	return true
}

func (c *Consultant) Move(place string) {
	fmt.Printf("%s moves to %s\n", c.Name, place)
	if c.Location != place {
		c.LocationChanged.Fire(c)
		if c.AvailableAt(place) != c.AvailableAt(c.Location) {
			c.AvailabilityChanged.Fire(c)
		}
		c.Location = place
	}
}

type EventAggregator struct {
	Changed, Location, Availability Signal
}

func (a *EventAggregator) Listen(c *Consultant) {
	c.LocationChanged.Add(func(x *Consultant) { a.signal(a.Location, x) })
	c.AvailabilityChanged.Add(func(x *Consultant) { a.signal(a.Availability, x) })
}

func (a *EventAggregator) signal(specific Signal, c *Consultant) {
	specific.Fire(c)  // the specific event
	a.Changed.Fire(c) // and the general one
}

func main() {
	agg := &EventAggregator{}
	alice := &Consultant{Name: "alice", Home: "London", AvailableAtHome: false, Location: "London"}
	bob := &Consultant{Name: "bob", Home: "Paris", AvailableAtHome: true, Location: "Lyon"}
	agg.Listen(alice)
	agg.Listen(bob)

	agg.Changed.Add(func(c *Consultant) { fmt.Printf("screen: %s changed\n", c.Name) })
	agg.Availability.Add(func(c *Consultant) { fmt.Printf("phone: availability of %s changed\n", c.Name) })

	alice.Move("Leeds")
	bob.Move("Paris")
}
Output
alice moves to Leeds
screen: alice changed
phone: availability of alice changed
screen: alice changed
bob moves to Paris
screen: bob changed
  • Verdict: idiom. Slices of functions are the events.
RustGitHub
use std::cell::RefCell;
use std::rc::Rc;

type Handler = Box<dyn Fn(&str)>;

#[derive(Default)]
struct Signal(Vec<Handler>);

impl Signal {
    fn add(&mut self, h: impl Fn(&str) + 'static) {
        self.0.push(Box::new(h));
    }
    fn fire(&self, name: &str) {
        for h in &self.0 {
            h(name);
        }
    }
}

struct Consultant {
    name: String,
    home: String,
    available_at_home: bool,
    location: String,
    location_changed: Signal,
    availability_changed: Signal,
}

impl Consultant {
    fn new(name: &str, home: &str, available_at_home: bool, location: &str) -> Self {
        Consultant {
            name: name.into(),
            home: home.into(),
            available_at_home,
            location: location.into(),
            location_changed: Signal::default(),
            availability_changed: Signal::default(),
        }
    }
    fn available_at(&self, place: &str) -> bool {
        if place == self.home { self.available_at_home } else { true }
    }
    fn move_to(&mut self, place: &str) {
        println!("{} moves to {}", self.name, place);
        if self.location != place {
            self.location_changed.fire(&self.name);
            if self.available_at(place) != self.available_at(&self.location) {
                self.availability_changed.fire(&self.name);
            }
            self.location = place.into();
        }
    }
}

#[derive(Default)]
struct EventAggregator {
    changed: Signal,
    location: Signal,
    availability: Signal,
}

fn listen(agg: &Rc<RefCell<EventAggregator>>, c: &mut Consultant) {
    let a = Rc::clone(agg);
    c.location_changed.add(move |n| {
        let a = a.borrow();
        a.location.fire(n); // the specific event
        a.changed.fire(n); // and the general one
    });
    let a = Rc::clone(agg);
    c.availability_changed.add(move |n| {
        let a = a.borrow();
        a.availability.fire(n);
        a.changed.fire(n);
    });
}

fn main() {
    let agg = Rc::new(RefCell::new(EventAggregator::default()));
    let mut alice = Consultant::new("alice", "London", false, "London");
    let mut bob = Consultant::new("bob", "Paris", true, "Lyon");
    listen(&agg, &mut alice);
    listen(&agg, &mut bob);

    agg.borrow_mut().changed.add(|n| println!("screen: {} changed", n));
    agg.borrow_mut().availability.add(|n| println!("phone: availability of {} changed", n));

    alice.move_to("Leeds");
    bob.move_to("Paris");
}
Output
alice moves to Leeds
screen: alice changed
phone: availability of alice changed
screen: alice changed
bob moves to Paris
screen: bob changed
  • Verdict: idiom. Vectors of boxed closures are the events. The consultants share the aggregator through Rc<RefCell<...>>.

Consequences

The benefits:

  • The registration logic is in one place, not in each observer.1
  • An aggregator also simplifies the memory management issues in using observers.1
  • Publishers and subscribers are decoupled, so they can evolve independently. New modules can be added that respond to events that other modules define.2

The costs:

  • A generic event simplifies registration, but observers are notified of events that may not have any material effect on them.1 In the example, the screen gets two notifications for one move of Alice.
  • An Event Aggregator is based on Observer, so all the danger areas of Observer apply.1

Without an aggregator, each client registers with each source. When a new source is added, each client must register with it, or the client misses its events. Here the screen did not register with Carol, who joined later:

This code runs but gives a wrong answer on purpose.

class Consultant:
    def __init__(self, name):
        self.name, self.handlers = name, []

    def move(self, place):
        print(f"{self.name} moves to {place}")
        for h in self.handlers:
            h(self)


def screen(c):
    print(f"screen: {c.name} changed")


staff = [Consultant("alice"), Consultant("bob")]
for c in staff:
    c.handlers.append(screen)  # the screen registers with each consultant
staff.append(Consultant("carol"))  # joins later; nobody registers

staff[0].move("Leeds")
staff[2].move("Rome")  # the screen is not told
Output
alice moves to Leeds
screen: alice changed
carol moves to Rome

When not to use it

  • There are few event sources, and the client can register with each of them directly.1
  • Each client needs the full detail of the specific events of one source. Fowler suggests a single coarse-grained event for most cases.1
  • Facade and Adapter. An Event Aggregator is a particular form of Facade that focuses only on observer relationships.1 When it converts events into other events, it also acts as an Adapter.1
  • Events by type. In the Composite Application Library, the aggregator keeps a collection of the events in the system, and publishers and subscribers use it to locate an event. The aggregator constructs an event on its first access, so the publisher or subscriber does not need to determine whether the event is available.2 Here the publisher and the subscriber get the same event from the aggregator:
class Event:
    def __init__(self):
        self.subscribers = []

    def subscribe(self, action):
        self.subscribers.append(action)

    def publish(self, payload):
        for action in self.subscribers:
            action(payload)


class OrderSaved(Event):
    pass


class EventAggregator:
    def __init__(self):
        self.events = {}

    def get_event(self, event_type):
        if event_type not in self.events:  # built on first access
            self.events[event_type] = event_type()
        return self.events[event_type]


bus = EventAggregator()
bus.get_event(OrderSaved).subscribe(lambda n: print("mail: order", n))
bus.get_event(OrderSaved).subscribe(lambda n: print("audit: order", n))
bus.get_event(OrderSaved).publish(42)  # the publisher knows no subscriber
Output
mail: order 42
audit: order 42
  • Weak references. A Prism event can hold a weak delegate reference to the subscriber. This reference does not prevent garbage collection of the subscriber, so the subscriber does not need to unsubscribe.2
  • Observer. An Event Aggregator is based on Observer. It observes the source objects, and the clients observe it.1

Known uses

  • Prism. The class EventAggregator keeps a dictionary from event types to events. Its method GetEvent<TEventType>() gets the single instance of the event managed by this aggregator: multiple calls with the same type return the same event instance.3 The CompositePresentationEvent class of the earlier Composite Application Library keeps the list of subscribers and dispatches events to them.2
  • Fowler's consultant screen. Fowler's C# example registers for the LocationChanged and AvailabilityChanged events of each consultant, and signals ConsultantChanged, ConsultantLocationChanged and ConsultantAvailabilityChanged.1

References

  1. Martin Fowler, Event Aggregator, summary; How it Works; When to Use It; Further Reading; Example, Watching Our Consultants (C#)
  2. Event Aggregator, Composite Application Guidance, Microsoft Learn, IEventAggregator; CompositePresentationEvent; Subscribing to an Event
  3. Prism v8.1.97 source, src/Prism.Core/Events/EventAggregator.cs, class EventAggregator and GetEvent, lines 12 to 44

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/GM2N7C/text.yaml