原生实现三步曲:事件总线通常实现了订阅者模式,订阅者模式包含发布者和订阅者两种角色。

a.抽象类的定义

  1. //发布者
  2. abstract class MyPublisher {
  3. void post<T>(T event);
  4. }
  5. //订阅者
  6. typedef MySubscriber<T> = void Function(T event);
  7. //抽象类继承
  8. abstract class _EventBus extends MyPublisher {
  9. void register<T>(MySubscriber<T> subscriber);
  10. void unregister<T>(MySubscriber<T> subscriber);
  11. }

b.接口的实现

  1. class MyEventBus implements _EventBus {
  2. //私有构造函数
  3. MyEventBus._internal();
  4. //保存单例
  5. static MyEventBus _singleton = MyEventBus._internal();
  6. //工厂构造函数
  7. factory MyEventBus()=> _singleton;
  8. List<Function> subscribers = new List();
  9. @override
  10. register<T>(MySubscriber<T> subscriber) {
  11. if (!subscribers.contains(subscriber)) {
  12. subscribers.add(subscriber);
  13. }
  14. }
  15. @override
  16. unregister<T>(MySubscriber<T> subscriber) {
  17. if (subscribers.contains(subscriber)) {
  18. subscribers.remove(subscriber);
  19. }
  20. }
  21. @override
  22. post<T>(T event) {
  23. var ints = subscribers.whereType<MySubscriber<T>>();
  24. ints?.forEach((subscriber) => subscriber?.call(event));
  25. }
  26. }

c.用法
场景:点击按钮,使得页面数字加一

  1. //定义事件A
  2. class EventA {int count = 0;}
  3. //按钮的点击
  4. var event = EventA();
  5. void _onTap() {
  6. event.count++;
  7. MyEventBus().post(event);
  8. }
  9. //定阅者初始化
  10. @override
  11. void initState() {
  12. super.initState();
  13. _subscriber = (EventA: event) => setState(() => _count = event.count);
  14. //注册
  15. MyEventBus().register<EventA>(_subscriber);
  16. }

Pub上的插件库: Github地址 — EventBus

  1. class GlobalHelper {
  2. //私有构造函数
  3. GlobalHelper._internal();
  4. //保存单例
  5. static GlobalHelper _singleton = GlobalHelper._internal();
  6. //工厂构造函数
  7. factory GlobalHelper()=> _singleton;
  8. static EventBus eventBus = EventBus(sync: true);
  9. }

自定义event事件

  1. //可以添加需要的属性值
  2. class MyEvent {
  3. MyEvent();
  4. }

自定义的事件监听

  1. GlobalHelper.eventBus.on<MyEvent>().listen((event) async {
  2. //do something
  3. });

事件的触发或发布

  1. GlobalHelper.eventBus.fire(MyEvent());

这样整个事件的广播机制就完成了。

EventBus中的实现机制

  1. /// Dispatches events to listeners using the Dart [Stream] API. The [EventBus]
  2. /// enables decoupled applications. It allows objects to interact without
  3. /// requiring to explicitly define listeners and keeping track of them.
  4. ///
  5. /// Not all events should be broadcasted through the [EventBus] but only those of
  6. /// general interest.
  7. ///
  8. /// Events are normal Dart objects. By specifying a class, listeners can
  9. /// filter events.

主要是用到了dart中的Stream:

  1. StreamController _streamController;

关于Stream可以看下一篇文章介绍