event_bus.dart 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /// 事件回调
  2. typedef EventCallback = void Function(dynamic arg);
  3. /// 事件总线
  4. class EventBus {
  5. EventBus._internal();
  6. static final EventBus _singleton = EventBus._internal();
  7. factory EventBus() => _singleton;
  8. // 保存事件订阅者的订阅关系,key:事件名(id),value: 对应事件的订阅者队列
  9. final _registry = <Object, List<EventCallback>?>{};
  10. /// 添加订阅者
  11. void register(eventName, EventCallback f) {
  12. _registry[eventName] ??= <EventCallback>[];
  13. _registry[eventName]!.add(f);
  14. }
  15. /// 移除订阅者
  16. void unRegister(eventName, [EventCallback? callback]) {
  17. var list = _registry[eventName];
  18. if (eventName == null || list == null) return;
  19. if (callback == null) {
  20. _registry[eventName] = null;
  21. } else {
  22. list.remove(callback);
  23. }
  24. }
  25. /// 发送事件
  26. void post(eventName, [arg]) {
  27. var list = _registry[eventName];
  28. if (list == null) return;
  29. int len = list.length - 1;
  30. // 反向遍历,防止订阅者在回调中移除自身带来的下标错位
  31. for (var i = len; i > -1; --i) {
  32. list[i](arg);
  33. }
  34. }
  35. }
  36. /// 暴露单例
  37. var eventBus = EventBus();