Widget Event Bus
---
Widget event bus is a simple implementation of observer pattern. It has a stream controller to broadcast widget events which is coming from to network layer to the widgets that listen for them.
* Upcoming events have two fields:
1. Widget event id (known as widgetEventKey)
2. Data
* Listener widgets listen to these events by using their own id
You can see the implementation of it below:
```gherkin=
@singleton
class NeoWidgetEventBus {
final _eventBus = StreamController<NeoWidgetEvent>.broadcast();
final Set<StreamSubscription<NeoWidgetEvent>> _subscriptions = {};
StreamSubscription<NeoWidgetEvent> listen({
required String eventId,
required Function(NeoWidgetEvent) onEventReceived,
}) {
final subscription = _eventBus.stream.listen((event) {
if (event.eventId == eventId) {
onEventReceived(event);
}
});
_subscriptions.add(subscription);
return subscription;
}
StreamSubscription<NeoWidgetEvent> listenEvents({
required List<String> eventIds,
required Function(NeoWidgetEvent) onEventReceived,
}) {
final subscription = _eventBus.stream.listen((event) {
if (eventIds.contains(event.eventId)) {
onEventReceived(event);
}
});
_subscriptions.add(subscription);
return subscription;
}
void addEvent(NeoWidgetEvent event) {
_eventBus.add(event);
}
void close() {
for (final subscription in _subscriptions) {
subscription.cancel();
}
_subscriptions.clear();
_eventBus.close();
}
}
```
```gherkin=
class NeoWidgetEvent {
final String eventId;
final Object? data;
NeoWidgetEvent({required this.eventId, this.data});
}
```