前情概要

  上一篇blog我们了解了EventBus中register/unregister的过程,对EventBus如何实现观察者模式有了基本的认识。今天我们来看一下它是如何分发一个特定事件的,即post(Object event)方法。

本篇概述

  EventBus中事件的分发与响应,post 方法。

post 方法

public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event); if (!postingState.isPosting) {
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}

  postingState(分发状态)具有ThreadLocal属性,包含一个eventQueue,用来保存当前线程分发中的event,在while循环中,逐一调用 postSingleEvent(eventQueue.remove(0), postingState),清空发送队列。

postSingleEvent 方法

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) {
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
if (!subscriptionFound) {
if (logNoSubscriberMessages) {
Log.d(TAG, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}

  这个方法用来分发单个事件,如果EventBus支持继承,则分发继承的所有基类事件;若没有找到订阅者,则根据logNoSubscribeMessages、sendNoSubscriberEvent这两个标志位处理相应的逻辑(打日志、发送NoSubscriberEvent事件)。

  再进一步,我们看看 postSingleEventForEventType 方法。

postSingleEventForEventType 方法

  在仔细阅读源代码之前,我们应该大致就能够猜想得到,这一步,理应是遍历该事件类型的订阅者列表,找到对应的订阅者后把事件发送出去;结合之前了解过的EventBus响应事件的四种模式(PostThread, MainThread, BackgroundThread, Async),接下来关注的重点是分发事件时如何处理这一段逻辑。

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
postToSubscription(subscription, event, postingState.isMainThread);
aborted = postingState.canceled;
} finally {
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
if (aborted) {
break;
}
}
return true;
}
return false;
}

  通过eventType找到对应的subscriptions后,逐一调用postToSubscription方法,其中对四种事件相应方式进行了处理。最终是通过反射进行了对应方法的调用。

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
case PostThread:
invokeSubscriber(subscription, event);
break;
case MainThread:
if (isMainThread) {
invokeSubscriber(subscription, event);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
case BackgroundThread:
if (isMainThread) {
backgroundPoster.enqueue(subscription, event);
} else {
invokeSubscriber(subscription, event);
}
break;
case Async:
asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}

总结

  分发事件的过程并不复杂,真正核心的一句话就可以概括:根据eventType找到对应的订阅者,通过反射进行具体方法调用。

下期预告

  四种线程模式实现方式解析。

[EventBus源码解析] EventBus.post 方法详述的更多相关文章

  1. [EventBus源码解析] EventBus.register 方法详述

    前情概要 在上一篇中,介绍了EventBus的基本使用方法,以及一部分进阶技巧.本篇及以后的几篇blog将会集中解析EventBus.java,看看作者是如何优雅地实现这个看似简单的事件分发/接收机制 ...

  2. EventBus源码解析 源码阅读记录

    EventBus源码阅读记录 repo地址: greenrobot/EventBus EventBus的构造 双重加锁的单例. static volatile EventBus defaultInst ...

  3. 【Android】EventBus 源码解析

    EventBus 源码解析 本文为 Android 开源项目实现原理解析 中 EventBus 部分项目地址:EventBus,分析的版本:ccc2771,Demo 地址:EventBus Demo分 ...

  4. Spring源码解析之八finishBeanFactoryInitialization方法即初始化单例bean

    Spring源码解析之八finishBeanFactoryInitialization方法即初始化单例bean 七千字长文深刻解读,Spirng中是如何初始化单例bean的,和面试中最常问的Sprin ...

  5. Android EventBus源码解析 带你深入理解EventBus

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/40920453,本文出自:[张鸿洋的博客] 上一篇带大家初步了解了EventBus ...

  6. 源码解析-EventBus

    示例使用 时序图 源码解读 EventBus 使用 官网定义:EventBus 是一个使用 Java 写的观察者模式,解耦的 Android 开源库.EventBus 只需要几行代码即可解耦简化代码, ...

  7. 多线程爬坑之路-Thread和Runable源码解析之基本方法的运用实例

    前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...

  8. [Java多线程]-Thread和Runable源码解析之基本方法的运用实例

    前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...

  9. EventBus源码解析

    用例 本文主要按照如下例子展开: //1. 新建bus对象,默认仅能在主线程上对消息进行调度 Bus bus = new Bus(); // maybe singleton //2. 新建类A(sub ...

随机推荐

  1. mysq常见问题

    1.Reading table information for completion of table and column names You can turn off this feature t ...

  2. iOS移动下上传图片失败解决 (上传多图,带其他参数)

    项目中有一个主要的功能,就是上传图片,结结果移动真的是很奇怪,WiFi,联通,电信都没有问题的情况下,居然在移动下不行,真的是很头疼.不过好在最后是解决了 项目的网络请求我是采用ASIHttpRequ ...

  3. Android常见控件— — —ProgressBar

    ProgressBar用于在界面上显示一个进度条,表示我们的程序正在加载一些数据. <?xml version="1.0" encoding="utf-8" ...

  4. 2016 - 1 - 24 CSS初步

    1.The difference between CSS and HTML HTML document is that it specities the content of the page. An ...

  5. SVD小结

    1.矩阵分解 假设一个矩阵Data是m行n列,SVD(奇异值分解)将Data分解为U,E,VT 三个矩阵: Datam*n=Um*kEk*kVTk*n E是一个对角矩阵,对角元素为奇异值,对应Data ...

  6. BZOJ 3110 树套树 && 永久化标记

    感觉树套树是个非常高深的数据结构.从来没写过 #include <iostream> #include <cstdio> #include <algorithm> ...

  7. 解决ASP.NET 自定义报表部署到IIS浏览时出现ASP.NET会话已结束问题

    进到公司开始接触的项目就要做报表,原系统使用的是水晶报表,但是水晶报表展示方面美观方面不怎么好需客户需要美化一下.自定义报表与水晶报表之前都没有接触过,自己先学了一下这两种报表,后面觉得自定义报表设计 ...

  8. Python::OS 模块 -- 简介

    OS 模块简介 OS模块是Python标准库中的一个用于访问操作系统功能的模块,OS模块提供了一种可移植的方法使用操作系统的功能.使用OS模块中提供的接口,可以实现跨平台访问.但是在OS模块中的接口并 ...

  9. IPC-管道

    内容提要: 管道简介 使用无名管道实现一个简单的本地文件服务器 使用标准I/O函数库提供的管道实现 使用popen实现本地文件服务器 有名管道-FIFO 使用FIFO改写本地文件服务器 管道和FIFO ...

  10. Android studio工具介绍

    区域1介绍 这个区域是运行和调试相关的操作. 1.编译2中显示的模块                      2.当前项目的模块列表            3.运行2中显示的模块           ...