Event Bus and Messaging
Systems should not call each other directly. If the damage system calls audio.play("hit"), ui.flashHealthBar() and achievements.check(), it now depends on three subsystems and every new reaction means editing damage code. An event bus inverts that: the damage system publishes a DamageTaken event, and anything that cares subscribes to it.
The gameplay view of events is covered in Game Events. This lesson builds the engine part: a type-safe bus, the difference between immediate and queued dispatch, and the traps.
A typed bus with immediate dispatch
Each event is a plain struct. The bus keeps, per event type, a list of handler functions. publish calls them right away, in subscription order.
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <typeindex>
#include <unordered_map>
#include <vector>
class EventBus {
public:
template <typename E> using Handler = std::function<void(const E&)>;
template <typename E> void subscribe(Handler<E> h) { list<E>().push_back(std::move(h)); }
template <typename E> void publish(const E& event) {
for (auto& h : list<E>()) h(event);
}
private:
struct IList { virtual ~IList() = default; };
template <typename E> struct List : IList { std::vector<Handler<E>> handlers; };
template <typename E> std::vector<Handler<E>>& list() {
auto& slot = lists_[std::type_index(typeid(E))];
if (!slot) slot = std::make_unique<List<E>>();
return static_cast<List<E>&>(*slot).handlers;
}
std::unordered_map<std::type_index, std::unique_ptr<IList>> lists_;
};
struct DamageTaken { int entity; int amount; };
struct EnemyKilled { int entity; std::string by; };
int main() {
EventBus bus;
int score = 0;
bus.subscribe<DamageTaken>([](const DamageTaken& e) { std::cout << "[audio] hit sound for entity " << e.entity << "\n"; });
bus.subscribe<DamageTaken>([](const DamageTaken& e) { std::cout << "[ui] health bar -" << e.amount << "\n"; });
bus.subscribe<EnemyKilled>([&score](const EnemyKilled& e) { score += 100; std::cout << "[score] " << e.by << " killed " << e.entity << ", score " << score << "\n"; });
// The damage system knows nothing about audio, UI or score.
bus.publish(DamageTaken{7, 25});
bus.publish(EnemyKilled{7, "player"});
bus.publish(DamageTaken{3, 10});
}[audio] hit sound for entity 7
[ui] health bar -25
[score] player killed 7, score 100
[audio] hit sound for entity 3
[ui] health bar -10
The template keeps it type-safe: a handler for DamageTaken can only receive DamageTaken. No void* casts, no string event names.
The trouble with immediate dispatch
Immediate dispatch is simple, but the handler runs inside the publisher's code, in the middle of its loop. Three classic bugs follow:
- Re-entrancy. A handler publishes another event, whose handler publishes the first one again. Deep call stacks, or infinite recursion.
- Iterator invalidation. The damage system iterates enemies; an
EnemyKilledhandler destroys the entity and erases it from the container being iterated. - Order surprises. The UI shows the new health before the physics system has even run this frame.
The usual answer is a queued (deferred) bus: publish only stores the event; dispatch() delivers everything at a well-defined point in the frame. Events published during dispatch go into the next batch, so one dispatch call cannot loop forever.
#include <functional>
#include <iostream>
#include <string>
#include <variant>
#include <vector>
struct DamageTaken { int entity; int amount; };
struct EnemyKilled { int entity; };
struct SpawnLoot { int entity; };
using Event = std::variant<DamageTaken, EnemyKilled, SpawnLoot>;
class QueuedBus {
public:
void publish(Event e) { pending_.push_back(std::move(e)); }
void onEvent(std::function<void(const Event&, QueuedBus&)> h) { handlers_.push_back(std::move(h)); }
// Deliver everything queued so far; events raised by handlers wait for the next call.
int dispatch() {
std::vector<Event> batch;
batch.swap(pending_);
for (const Event& e : batch)
for (auto& h : handlers_) h(e, *this);
return int(batch.size());
}
bool empty() const { return pending_.empty(); }
private:
std::vector<Event> pending_;
std::vector<std::function<void(const Event&, QueuedBus&)>> handlers_;
};
int main() {
QueuedBus bus;
std::vector<int> health = {30, 50, 20};
bus.onEvent([&health](const Event& ev, QueuedBus& b) {
if (auto* d = std::get_if<DamageTaken>(&ev)) {
health[d->entity] -= d->amount;
std::cout << " entity " << d->entity << " health " << health[d->entity] << "\n";
if (health[d->entity] <= 0) b.publish(EnemyKilled{d->entity}); // queued, not delivered now
} else if (auto* k = std::get_if<EnemyKilled>(&ev)) {
std::cout << " entity " << k->entity << " died\n";
b.publish(SpawnLoot{k->entity});
} else if (auto* l = std::get_if<SpawnLoot>(&ev)) {
std::cout << " loot dropped at entity " << l->entity << "\n";
}
});
// Gameplay this frame: an explosion hits everyone. Iterating health is safe; nothing is delivered yet.
for (int e = 0; e < int(health.size()); e++) bus.publish(DamageTaken{e, 25});
int pass = 1;
while (!bus.empty()) {
std::cout << "dispatch pass " << pass << ":\n";
int n = bus.dispatch();
std::cout << " (" << n << " events)\n";
pass++;
}
}dispatch pass 1:
entity 0 health 5
entity 1 health 25
entity 2 health -5
(3 events)
dispatch pass 2:
entity 2 died
(1 events)
dispatch pass 3:
loot dropped at entity 2
(1 events)
The explosion loop never saw a handler run under it. Each wave of consequences (damage, then deaths, then loot) is its own pass. A real engine usually calls dispatch at fixed points in the frame and caps the number of passes, logging a warning if events still keep coming.
Choosing a style
| Style | When to use | Watch out for |
|---|---|---|
Immediate (publish calls handlers) |
UI callbacks, editor tools, rare events where the reaction must happen now | re-entrancy, modifying containers being iterated |
| Queued, per frame | gameplay events (damage, deaths, pickups), anything crossing systems | one-frame delay; the event must carry copies, not pointers that may dangle |
| Per-type queues read by systems (ECS "event components" or channels) | high-volume events, multithreaded systems | consumers must read every frame or events pile up |
Tip: Events should carry IDs and values, never raw pointers to entities. By the time a queued event is delivered, the entity may be gone. Use generational handles so a stale ID can be detected.
Note: Unsubscribing matters. A handler that captures
thisof an object that has been destroyed will crash on the next event. Return a subscription token fromsubscribe(an RAII object that unsubscribes in its destructor) so lifetimes are tied together. See RAII, Ownership and Lifetimes.
An event bus makes code loosely coupled, and also harder to follow: "who reacts to EnemyKilled?" is now a search instead of a function call. Add a debug option that logs every published event with its frame number. It turns most event bugs into a five-minute read.
Test yourself
What is the main advantage of a queued event bus over immediate dispatch?
- Events are delivered faster
- Handlers run at a defined point in the frame, not inside the publisher's loop
- It needs no handlers
- It removes the need for event types
In the queued example, why does SpawnLoot arrive in a later dispatch pass than EnemyKilled?
- Because variants are slow
- Because events published during a dispatch are queued for the next batch
- Because handlers run in reverse order
- Because loot has a lower priority
What should a queued event carry to refer to an entity?
- A raw pointer to the entity object
- A reference to its component
- An ID or generational handle
- Nothing; handlers search for it