EventBus总结(原)

1、EventBus的作用

  EventBus is a publish/subscribe event bus for Android and Java.

  EventBus可以被用来在各种自定义的监听事件中使用,包括不限于Activity、Fragment、Service等等等等需要进行数据传递的地方,不过应该只局限于app内部。

2、EventBus的原理

  

  EventBus是一个典型的事件分发器,Observer模式。订阅者被集中到EventBus类中,当发布者通过post MessageEvent时,通知到订阅者。

3、EventBus的实现

  

    将订阅者注册到EventBus时,EventBus通过SubscriberMethodFinder反射扫描annotation @Subscribe,将注册者中的通知方法都存储在结构体中并返回给EventBus中的

subscriptionsByEventType结构体,这个结构体根据自定义的消息类型进行map存入,并且将该订阅者所有的自定义消息类型都放入结构体typesBySubscriber中。
    当发布自定义的消息时,EventBus从subscriptionsByEventType结构体中取出对应的消息method,invoke对应方法。

    当移除订阅者时,根据此订阅者检索typesBySubscriber,从subscriptionsByEventType结构体中移除所有该订阅者的方法。

4、EventBus的流程(此图看不清时请下载或者放大查看)

  

5、EventBus的使用

  5.1 定义订阅者需要传递的消息类型;对于不同的功能要定义不同的消息,同一个订阅者可以存在不同的消息类型;

  5.2 在订阅者中使用@Subscribe注解方法,方法一定要是public | (Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC);

  5.3 将订阅者注册到EventBus,可以使用EventBus的builder方法或者EventBusBuilder进行EventBus的定制;

  5.4 post方法将自定义消息推送到订阅者;注意,由于在EventBus中使用了ThreadLocal的list,更好的支持多线程操作;而post时选择的最终消息推送线程,则由@Subscribe的注解方法中的参数ThreadMode决定;

  5.5 注意要在不使用时unregister订阅者;

  5.6 具体代码可参考EventBus github页面。 (https://github.com/greenrobot/EventBus)   

  1. Define events:

    public static class MessageEvent { /* Additional fields if needed */ }
  2. Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

    @Subscribe(threadMode = ThreadMode.MAIN)  
    public void onMessageEvent(MessageEvent event) {/* Do something */};

    Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

     @Override
     public void onStart() {
         super.onStart();
         EventBus.getDefault().register(this);
     }
    
     @Override
     public void onStop() {
         super.onStop();
         EventBus.getDefault().unregister(this);
     }
  3. Post events:

     EventBus.getDefault().post(new MessageEvent());

    that's ok.
原文地址:https://www.cnblogs.com/weizhxa/p/9762286.html