美文网首页
Eventbus源码走读

Eventbus源码走读

作者: wlpgdd0725 | 来源:发表于2019-03-14 13:37 被阅读0次

1.Eventbus通过DCL单例模式获取实例

DCL单例

2.在onCreate中进行register,在onDestory中进行unregister

register(this)是干嘛的呢?其实register(this)就是去当前类,遍历所有的方法,找到onEvent开头的然后进行存储

最终调用该方法

参数1.this就是类,参数2为onEvent写死,4.是优先级,越高越先被处理

返回当前类中Onevent开头的方法list

subscriptionsByEventType是个Map,key:eventType ; value:CopyOnWriteArrayList ; 这个Map其实就是EventBus存储方法的地方,一定要记住!

扫描了所有的方法,把匹配的方法最终保存在subscriptionsByEventType(Map,key:eventType ; value:CopyOnWriteArrayList<Subscription> )中

3.发布

EventBus.getDefault().post(param);

把这个param发布出去,EventBus会在它内部存储的方法中,进行扫描,找到参数匹配的,就使用反射进行调用。

Threadlocal线程隔离

遍历队列中的所有的event,调用postSingleEvent(eventQueue.remove(0), postingState)方法。

postSingleEvent历所有的Class,到subscriptionsByEventType去查找subscriptions

void invokeSubscriber(Subscription subscription, Object event) throws Error {

            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);

  }

直接反射调用;也就是说在当前的线程直接调用该方法;

register会把当前类中匹配的方法,存入一个map,而post会根据实参去map查找进行反射调用。分析这么久,一句话就说完了~~

public void onEventMainThread(param){}

public void onEventPostThread(param)

public void onEventBackgroundThread(param)

public void onEventAsync(param)

相关文章

网友评论

      本文标题:Eventbus源码走读

      本文链接:https://www.haomeiwen.com/subject/lqxqmqtx.html