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(方法参数)) 执行订阅方法
本文介绍了EventBus的基本使用步骤:注册、取消订阅、定义事件订阅方法及发送事件;并阐述了其基本工作原理:通过保存对象与订阅方法的对应关系,并在发送事件时查找匹配的订阅方法。
773

被折叠的 条评论
为什么被折叠?



