首页 > 代码库 > EventBus 3.0 源码简要分析

EventBus 3.0 源码简要分析

EvenBus 可以在不同模块间传递信息,减少接口的使用。


一、使用例子

<span style="font-size:18px;">public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EventBus.getDefault().register(this);

        testEventBus();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getData(String result){
        Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
    }

    private void testEventBus(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5 * 1000);
                    
                    EventBus.getDefault().post("这是 EventBus 的测试");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }
}</span>


二、注册 

EventBus.getDefault().regiser(this);

    EventBus 负责对外提供 API .

(1)getDefault() 获得 EventBus 实例,使用了 volatile 和 单例模式

<span style="font-size:18px;">   static volatile EventBus defaultInstance;
    /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }</span>


new EventBus() 构建对象的时候,使用了 Builder 模式

<span style="font-size:14px;">  public EventBus() {
        this(DEFAULT_BUILDER);
    }

    EventBus(EventBusBuilder builder) {
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);     // 一个主线程的 Handler
        backgroundPoster = new BackgroundPoster(this);   // Runnable
        asyncPoster = new AsyncPoster(this);
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        throwSubscriberException = builder.throwSubscriberException;
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;
    }</span>


(2) register(Object subscriber)  过程

 EventBus 有几个重要的成员变量,在我们进行流程分析前,先看看

    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    private final Map<Object, List<Class<?>>> typesBySubscriber;

    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

subscripitonsByEventType 和 typesBySubcriber 都是 HashMap, 在上面构建新的 EventBus 对象时初始化。

其中 subcriptionsByEventType 是以eventType 为 key ,Subcription 列表为 value; 而 typesBySubcriber 是以 订阅者 subcriber 为 key, 订阅事件 SubcribedEvents 列表为 value 的。

技术分享


Subcription 类有三个成员变量

    final Object subscriber;
    final SubscriberMethod subscriberMethod;
    /**
     * Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery
     * {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions.
     */
    volatile boolean active;

其中 subcriber 与 typesBySubcriber 中的 key 联系起来。

currentPostingThreadState 是一个 ThreadLocal ,存放 PostingThreadState , 用于监听整个post 过程,关于 ThreadLocal 的详细内容,可去看任玉刚的《Android 开发探索艺术》一书。


 下面是注册的整个大概流程:

主线:

技术分享


 EventBus.java 中

  public void register(Object subscriber) {
        // 返回一个 Class 类型的实例
        Class<?> subscriberClass = subscriber.getClass();  // 例如 com.yxhuang.mytestapplication.MainActivity
        //  获取订阅的方法, 内部最终时通过注解是方式获得订阅的方法
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            // 添加到 subscriptionsByEventType
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            // 如果已经注册过,则抛出异样,防止重复注册
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType);
            }
        }

        // 根据优先级添加到 CopyOnWriteArrayList 中
        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        // 添加到 Map<Object, List<Class<?>>>  typesBySubscriber
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        if (subscriberMethod.sticky) {  // 是否为粘性方法
            if (eventInheritance) {  // 默认是 false
                // Existing sticky events of all subclasses of eventType have to be considered.
                // Note: Iterating over all events may be inefficient with lots of sticky events,
                // thus data structure should be changed to allow a more efficient lookup
                // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
                Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry<Class<?>, Object> entry : entries) {
                    Class<?> candidateEventType = entry.getKey();

                    // When using instanceof, you need to know the class of "B" at compile time. When using isAssignableFrom()
                    // it can be dynamic and change during runtime.
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

整体的过程还是比较简洁的

1、以 subcriber 的 class 作为 key , 传进 subcriberMethodFinder.findSubcriMethods( ...)  方法中,并得到一个所有订阅方法的 list;

2、调用 subcribe () 方法,将所有的订阅方法相应放到  subcriptionsByEventType 和 typesByScriber 中,如果是粘性订阅方法,则进行相应的处理。


粘性方法的处理, 最终都会调用 checkPostStickEventToSubcriptions(...) 方法

    private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        if (stickyEvent != null) {
            // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
            // --> Strange corner case, which we don't take care of here.
            // 根据不同的 ThreadMode 进行分发
            postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
        }
    }

在这个方法里面最后调用了 postToSubcription(...) 方法,分发相应的订阅结果,我们在后面的 post 过程中有分析。可见如果订阅方法是粘性的,则不需要调用 EventBus.post(...) 方法,在注册之后,就会自行分发结果。


我们再来看看注册过程是如何得到所有订阅方法的。

从 subcriberMethodFinder.findSucriberMethod(...) 进去

技术分享

 SucriberMethodFinder 类中

   // 是否忽略生成的 index
    private final boolean ignoreGeneratedIndex;   
    // 订阅缓存池
    private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
    // FindState 缓存池
    private static final int POOL_SIZE = 4;
    private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];

其中, FindState 类在查找订阅方法过程中使用


SucriberMethodFinder.findSucriberMethod(...)

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        // 先从缓存中获取, METHOD_CACHE   是一个 CurrentHashMap
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) {  // 是否忽略生成的 index 默认是 false
            // 使用反射获取单个类里面的订阅方法
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            // 放入缓存中并返回
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }
1、ignoreGeneratedIndex 默认是false , 只有使用索引生成,才会是 true ,调用 findUsingReflection(...) 方法,详细内容,可根据后面的推荐阅读中查看。我们这里走 findUsingInfo(...) 这个方法;

2、将查找的订阅方法放进缓存中,并返回;


    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            // 获取订阅者的信息
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {
                // 获取订阅的方法
                SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                for (SubscriberMethod subscriberMethod : array) {
                    // 检测订阅方法和订阅参数
                    if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                        findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
                // 利用反射查找自身的订阅方法
                findUsingReflectionInSingleClass(findState);
            }
            // 查找父类的订阅方法
            findState.moveToSuperclass();
        }
        // 返回所有的订阅方法,并释放掉 findState
        return getMethodsAndRelease(findState);
    }

  获取订阅者的信息

    private SubscriberInfo getSubscriberInfo(FindState findState) {
        // 获取父类订阅者的信息
        if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
            SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
            if (findState.clazz == superclassInfo.getSubscriberClass()) {
                return superclassInfo;
            }
        }
        // 默认是空的,是由使用了索引时,才会调用
        if (subscriberInfoIndexes != null) {  
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }

1.调用 getSubcriberInfo(...)  方法获取订阅者的信息;

  2.  调用  findUsingRelectionInSingleClass(...) ,用反射方法获得订阅方法;

  3.查找父类的订阅方法;

  4.释放掉 findState 并返回订阅方法;


这里我们重点看一下 FindState 和 如何利用反射得到订阅方法。先看 FindState

prepareFindState()  要和 getMethodsAndRelease() 方法一起看

private FindState prepareFindState() {
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                FindState state = FIND_STATE_POOL[i];
                if (state != null) {
                    FIND_STATE_POOL[i] = null;
                    return state;
                }
            }
        }
        return new FindState();
    }

    private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        findState.recycle();
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                if (FIND_STATE_POOL[i] == null) {
                    FIND_STATE_POOL[i] = findState;
                    break;
                }
            }
        }
        return subscriberMethods;
    }

FIND_STATE_POOL 是一个存有四个 FindState 对象的缓存池;

在 prepareFindState() 方法中,从 FIND_STATE_POOL 缓存池中取出一个 findState 对象并用一个 null 替代它在缓存池中的位置,然后将调用 FindState.initForSubcriber(..) 初始化 findState ; 在 getMethodsAndRelease(...) 方法中,将 findState 对象 recycle() 进行处理,然后查看 FIND_STATE_POOL 缓存池中那个位置为空,让后将这个处理后的 findState 放回缓存池中。

这样整个过程实现对 findState 对象的充分利用,减小因为频繁生成太多对象而占用太多的内存。


  SubcriberMethodFinder.findUsingRelectionInSingleClass(...) 方法

    private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // This is faster than getMethods, especially when subscribers are fat classes like Activities
            // 返回这个类或者接口全部的方法,但不包括超类继承了的方法
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
            // 返回所有的公有方法,包括从超类继承来的公有方法
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
        for (Method method : methods) {
            //  返回一个用于描述构造器,方法或域的修饰符的整型数值。使用 Modifiers 类中的这个方法可以分析这个返回值。
            int modifiers = method.getModifiers();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                // 返回一个用于描述参数类型的 Class 对象数组 (返回方法的参数)
                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 1) {
                    // 获得给定类型的注解,如果没有这样的注解,则返回 null
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        Class<?> eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            // 获得 ThreadMod 类型
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            // 生成一个 SubscriberMethod 对象,放到列表中
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    }
                } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                    String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                    throw new EventBusException("@Subscribe method " + methodName +
                            "must have exactly 1 parameter but has " + parameterTypes.length);
                }
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                // 方法不是 public 则抛出异样
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException(methodName +
                        " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
            }
        }
    }

1、Class.getDeclaredMethod() 而不是 getMethod() 方法,是因为 getDeclaredMethod() 只放回自身和接口的方法,而 getMethod() 不仅返回自身的方法而且还返回从父类的继承而来的公有方法,这样使用 getDeclaredMethod() 可以节约获取方法的时间;

2、我们在设置订阅方法时使用了 Subcribe 注解类,并设置了 ThreadMode 类型

例子:

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getData(String result){
        Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
    }
所以

<span style="font-size:18px;">// 获得给定类型的注解,如果没有这样的注解,则返回 null
  Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);</span>
   会获得这个方法的注解;


3、在获取 ThreadMode 之后,放到 findState 对象成员变量的列表中。


至此,整个注册过程基本上完成了。



三、Post 消息过程

技术分享

在整个 post 过程中使用了 PostingThreadState 辅助类

    /** For ThreadLocal, much faster to set (and get multiple values). */
    final static class PostingThreadState {
        // 存放 postEvent 事件列表
        final List<Object> eventQueue = new ArrayList<Object>();
        boolean isPosting;      // 是否处于 posting 状态
        boolean isMainThread;   //  是否为主线程
        Subscription subscription;      // 订阅信息
        Object event;
        boolean canceled;      // 是否被取消
    }

EventBus.post(...) 方法

  public void post(Object event) {
        // 中 ThreadLocal 中获取一个 PostingThreadState,  使用 ThreadLocal 传递对象,对整个 post 过程传递数据,不受不同线程的影响
        PostingThreadState postingState = currentPostingThreadState.get();      // currentPostingThreadState   是 ThreadLocal
        List<Object> eventQueue = postingState.eventQueue;   // ArrayList<>;
        eventQueue.add(event);   // 添加到列表中

        if (!postingState.isPosting) {
            // 是否为主线程
            postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
            // post 的状态
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {
                    // post 一个 event 事件
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }
1、将 post 的事件存放到队列中,设置一些 postingThreadState 一些内容;

2、从队列中取出一个 event 并调用 postSingleEvent(...) 方法,将 event 分发出去;

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {  // 默认是 false,开启索引之后才会调用
            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 {
            // post 出去
            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));
            }
        }
    }
没有开启索引,调用 postSingleEventForEventType(...) 方法


 private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            // 从 map 中取出该类型的所以订阅者列表 subscriptions
            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;
    }
根据 evntType 得到该事件类型的所有订阅者,并调用 postToSubcription(...) 方法将分发给所有订阅者。


// 根据不同的 ThreadMode 进行分发
    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {  // 如果是主线程中,
                    invokeSubscriber(subscription, event);  // 利用反射,实现方法的调用
                } else {
                    // 如果不是在主线程,则利用 Handler , mainThreadPoster 是一个 主线程的 Handler
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case BACKGROUND:    // 后台
                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);
        }
    }

根据不同的的 ThreadMode 进行不同的方法调用,这几种方法都比较简单,此处不表


invokeSubscriber(...) 方法使用了反射,最终调用订阅方法

    void invokeSubscriber(Subscription subscription, Object event) {
        try {
            // 利用反射,调用方法
            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
        } catch (InvocationTargetException e) {
            handleSubscriberException(subscription, event, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Unexpected exception", e);
        }
    }


至此, post 消息的过程基本完成。



四、解除注册 unregister(...)

解除注册过程也比较简单,在 typesBySubcriber 和 subcriptionsByEventType 的 Map 中将相应的值移除即可

    public synchronized void unregister(Object subscriber) {
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            typesBySubscriber.remove(subscriber);
        } else {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

   /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }


至此 EventBus 整个简要的分析过程结束了,相应了解更多的分析内容,可以参考下面的参考内容。


五、参考内容

点击可跳链接

1、EventBus 3.0 源代码分析 


2、EventBus 3.0 源码分析


3、老司机教你 “飙” EventBus 3





EventBus 3.0 源码简要分析