EventBus基本设计思路

EventBus基于观察者模式,如图,被观察者状态改变时通过post方法通知观察者。

这里写图片描述

一、首先是EventBus的基本使用

第一步

  • 在各组件中注册(如Activity的onCreate(),Fragment的onViewCreate())
EventBus.getDefault().register(this);

第二步

  • 取消订阅(如onPause()或onDestroy()中)
if (EventBus.getDefault().isRegistered(this)) {
    EventBus.getDefault().unregister(this);
}

第三步

  • 事件订阅(接收)方法
  • 使用@Subscribe method: must be public, non-static, and non-abstract
  • 只有一个参数
@Subscribe
public void onEventBusSubscribe(String mess) {
     Log.e("TAG",mess);
}

第四步

  • 发送事件(如在Activity,Fragment,BroadcastReceiver…中)
  • post的类型须是某个订阅方法中的参数
EventBus.getDefault().post("msg");

二、基本原理

1、在register(this)时,将对象与订阅方法保存在Map中
2、在post时,通过post的参数类型找出订阅方法参数一致的方法及对于的对象,在通过 method.invoke(object(方法所在的对象),object(方法参数)) 执行订阅方法

猜你喜欢

转载自blog.csdn.net/PromiseTo/article/details/51272873