event_bus.dart 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //订阅者回调签名
  2. typedef void EventCallback(dynamic arg);
  3. /*
  4. Subscription? subscribe;
  5. void registerEventBus() {
  6. subscribe = bus.on(AppConstant.eventProfileRefresh, (arg) {
  7. Log.d("Home - 接收消息");
  8. });
  9. }
  10. void unregisterEventBus() {
  11. bus.off(AppConstant.eventProfileRefresh, subscribe);
  12. Log.d("Home - 解注册这个Key的消息");
  13. }
  14. //发送事件
  15. bus.emit(AppConstant.eventProfileRefresh, true);
  16. */
  17. //定义一个top-level(全局)变量,页面引入该文件后可以直接使用bus
  18. var bus = EventBus();
  19. class EventBus {
  20. EventBus._internal();
  21. //保存单例
  22. static final EventBus _singleton = EventBus._internal();
  23. //工厂构造函数
  24. factory EventBus() => _singleton;
  25. final _subscriptions = <String, List<Subscription>>{};
  26. /// 添加订阅者,返回一个 Subscription 对象,用于取消订阅
  27. Subscription on(String eventName, EventCallback callback) {
  28. final sub = Subscription(eventName: eventName, callback: callback);
  29. _subscriptions.putIfAbsent(eventName, () => []).add(sub);
  30. return sub;
  31. }
  32. /// 取消订阅(如果指定了 callback,则只取消对应的订阅者;否则取消所有订阅者)
  33. void off(String eventName, [Subscription? subscription]) {
  34. if (_subscriptions.containsKey(eventName)) {
  35. if (subscription == null) {
  36. _subscriptions[eventName]!.clear();
  37. } else {
  38. _subscriptions[eventName]!.removeWhere((sub) => sub.callback == subscription.callback);
  39. }
  40. }
  41. }
  42. /// 取消所有订阅
  43. void offAll() {
  44. _subscriptions.clear();
  45. }
  46. /// 触发事件,通知所有订阅者
  47. void emit(String eventName, [arg]) {
  48. for (final sub in _subscriptions[eventName] ?? []) {
  49. sub.callback(arg);
  50. }
  51. }
  52. }
  53. /// Subscription 对象,用于取消订阅
  54. class Subscription {
  55. final String eventName;
  56. final EventCallback callback;
  57. Subscription({required this.eventName, required this.callback});
  58. }