Common System 0.2.0
Common interfaces and patterns for system integration
Loading...
Searching...
No Matches
event_bus_example.cpp
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2021-2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
13
15
16#include <iostream>
17#include <string>
18
19using namespace kcenon::common;
20
21// Custom event types
23{
24 std::string username;
25 std::string ip_address;
26};
27
29{
31 double total;
32};
33
35{
36 std::string message;
38};
39
40int main()
41{
42 std::cout << "=== Event Bus Example ===\n\n";
43
44 auto& bus = get_event_bus();
45
46 // Subscribe to user login events
47 std::cout << "1. Subscribing to events...\n";
48 auto login_sub = bus.subscribe<user_logged_in>(
49 [](const user_logged_in& e)
50 { std::cout << " [Auth] User '" << e.username << "' logged in from " << e.ip_address << "\n"; });
51
52 auto audit_sub = bus.subscribe<user_logged_in>(
53 [](const user_logged_in& e)
54 { std::cout << " [Audit] Login recorded for '" << e.username << "'\n"; });
55
56 // Subscribe to order events
57 auto order_sub = bus.subscribe<order_placed>(
58 [](const order_placed& e)
59 { std::cout << " [Orders] Order #" << e.order_id << " placed, total: $" << e.total << "\n"; });
60
61 // Set error callback
62 bus.set_error_callback([](const std::string& error, size_t, uint64_t)
63 { std::cerr << " [Error] Event bus error: " << error << "\n"; });
64
65 // Publish events
66 std::cout << "\n2. Publishing events...\n";
67 bus.publish(user_logged_in{"alice", "192.168.1.100"});
68 bus.publish(order_placed{1001, 59.99});
69
70 // Unsubscribe audit logger
71 std::cout << "\n3. Unsubscribing audit logger...\n";
72 bus.unsubscribe(audit_sub);
73
74 // Publish again — only auth handler receives
75 std::cout << "\n4. Publishing after unsubscribe...\n";
76 bus.publish(user_logged_in{"bob", "10.0.0.1"});
77
78 // Priority ordering
79 std::cout << "\n5. Priority-ordered publishing...\n";
80 auto alert_sub = bus.subscribe<system_alert>(
81 [](const system_alert& e)
82 { std::cout << " [Alert] severity=" << e.severity << ": " << e.message << "\n"; });
83
84 bus.publish(system_alert{"CPU usage high", 2}, event_priority::high);
85 bus.publish(system_alert{"Disk space low", 1}, event_priority::normal);
86
87 // Cleanup
88 bus.unsubscribe(login_sub);
89 bus.unsubscribe(order_sub);
90 bus.unsubscribe(alert_sub);
91
92 std::cout << "\nDone.\n";
93 return 0;
94}
Event bus abstraction and common events.
int main()
Core interfaces.
Definition adapter.h:21
simple_event_bus & get_event_bus()
Access the global event bus instance.
Definition event_bus.h:452
std::string message