01/
01.rs

1use simple_event_bus::{Event, EventBus, Subscriber};
2
3struct ExampleSubscriber {
4    pub name: String,
5}
6
7impl ExampleSubscriber {
8    pub fn new(name: String) -> ExampleSubscriber {
9        ExampleSubscriber { name }
10    }
11}
12
13impl Subscriber for ExampleSubscriber {
14    type Input = String;
15
16    fn on_event(&mut self, event: &Event<Self::Input>) {
17        println!("{} received message: {}", self.name, event.get_data());
18    }
19}
20
21fn main() {
22    let mut event_bus = EventBus::new();
23
24    // We have to manually create and add each subscriber to the event bus.
25    event_bus.subscribe_listener(ExampleSubscriber::new("Subscriber 1".to_string()));
26    event_bus.subscribe_listener(ExampleSubscriber::new("Subscriber 2".to_string()));
27
28    // We can manually define an event and publish it to the event bus.
29    event_bus.publish(Event::new("hello".to_string()));
30    event_bus.publish(Event::new("world".to_string()));
31
32    // Alternatively, we can use the From trait to define an event and publish it to the event bus.
33    // This is as simple as using ".into()" on the data (so long as it matches the event bus's type parameter).
34    event_bus.publish("!".to_string().into());
35
36    // Here we show another example, this time directly from a String instead of using &str.
37    let test_string = String::from("Hello, World!");
38    event_bus.publish(test_string.into());
39
40    // Runs through each event, and calls each listener's on_event method.
41    event_bus.run();
42}