文档介绍:
简述:
在项目中,我们大多数开发者可能都使用过EventBus,即使没有使用过但我可以确定Android开发者也听说过这个牛X的库,,可见生命力极强呀。。
使用流程:
注册:
[html] view plain copy 在CODE上查看代码片派生到我的代码片
().register(obj)
订阅(消息接收):
[html] view plain copy 在CODE上查看代码片派生到我的代码片
***@Subscribe
public void receive(Object event){
}
发布消息:
[html] view plain copy 在CODE上查看代码片派生到我的代码片
().post(event)
注销:
[html] view plain copy 在CODE上查看代码片派生到我的代码片
().unregister(obj)
源码分析:
注册:
[html] view plain copy 在CODE上查看代码片派生到我的代码片
().register(obj)
这段代码做了两件事情:① () 创建EventBus对象;② register(obj) 方法为obj该类对象注册EventBus。那这两个方法究竟在EventBus中究竟做了哪些工作呢?我们打开EventBus的源码看一下:
1、()
源码如下:
[html] view plain copy 在CODE上查看代码片派生到我的代码片
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized () {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
看到了吧,EventBus采用单例模式创建EventBus对象,接下来它在构造方法中又做了什么事情呢?
[html] view plain copy 在CODE上查看代码片派生到我的代码片
public EventBus() {
this(DEFAULT_BUILDER);
}
在构造方法中其调用了有参构造方法:EventBus(EventBusBuilder builder ),我们再跟进去看一看:
[html] view plain copy 在CODE上查看代码片派生到我的代码片
EventBus(EventBusBuilder builder) {
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadPoster = new HandlerPoster(this, (), 10);
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
indexCount = != null ? () : 0;
//默认情况下参数为(null,false,false)
subscriberMethodFinder = new SubscriberMethodFinder(,
, );
logSubscriberExceptions =