| 1 | pub struct EventBus[T] { |
| 2 | mut: |
| 3 | subscribers map[string][]Subscriber[T] |
| 4 | } |
| 5 | |
| 6 | type EventType = string |
| 7 | type Subscriber[T] = fn (T) |
| 8 | |
| 9 | pub fn new_event_bus[T]() &EventBus[T] { |
| 10 | return &EventBus[T]{ |
| 11 | subscribers: map[string][]Subscriber[T]{} |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | fn (shared eb EventBus[T]) subscribe(event_type EventType, subscriber Subscriber[T]) { |
| 16 | lock eb { |
| 17 | if event_type !in eb.subscribers { |
| 18 | eb.subscribers[event_type] = []Subscriber[T]{} |
| 19 | } |
| 20 | |
| 21 | eb.subscribers[event_type] << subscriber |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | fn (shared eb EventBus[T]) publish(event_type EventType, data T) { |
| 26 | lock eb { |
| 27 | for _, subscriber in eb.subscribers[event_type] { |
| 28 | subscriber(data) |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn main() { |
| 34 | shared eb_string := new_event_bus[string]() |
| 35 | eb_string.subscribe('test', fn (data string) { |
| 36 | println(data) |
| 37 | }) |
| 38 | eb_string.publish('test', 'hello') |
| 39 | |
| 40 | shared eb_int := new_event_bus[int]() |
| 41 | eb_int.subscribe('test', fn (data int) { |
| 42 | println(data) |
| 43 | }) |
| 44 | eb_int.publish('test', 22) |
| 45 | } |
| 46 | |