分析EventBus源码时,发现了postSingleEvent方法中有一个神秘的lookupAllEventTypes,通过断点调试发现,该方法的主要作用是查找所有与特定事件相关的父类事件,也就是说,如果你对父事件订阅了,有多个子事件的情况下,无论发送哪个子事件,都可以在订阅父事件的地方统一处理
示例代码如下:
public class BaseEvent {
public String name;
public BaseEvent(String name){
this.name = name;
}
}
public class ChildEventA extends BaseEvent{
public ChildEventA(String name) {
super(name);
}
}
public class ChildEventB extends BaseEvent{
public ChildEventB(String name) {
super(name);
}
}
public class TestActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
EventBus.getDefault().register(new BaseEventSubscriber());
findViewById(R.id.tv_test).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(new ChildEventA("ChildEventA"));
EventBus.getDefault().post(new ChildEventB("ChildEventB"));
}
});
}
}
public class BaseEventSubscriber {
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(BaseEvent event) {
Log.i("BaseEventSubscriber","Received base event, name = "+ event.name);
}
}
运行结果: