05、Android--EventBus原理解析

EventBus原理

EventBus构造方法

当我们要使用EventBus时,首先会调用EventBus.getDefault()来获取EventBus实例。

public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
}

单例模式,采用了双重检查模式 (DCL)。接下来查看 EventBus 的构造方法:

public EventBus() {
    this(DEFAULT_BUILDER);
}

这里DEFAULT_BUILDER是默认的EventBusBuilder,用来构造EventBus:

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

this调用了EventBus的另一个构造方法,如下所示:

EventBus(EventBusBuilder builder) {
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
    backgroundPoster = new BackgroundPoster(this);
    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;
}

通过构造一个EventBusBuilder来对EventBus进行配置,这里采用了建造者模式。

订阅者注册

获取EventBus后,便可以将订阅者注册到EventBus中。下面来看一下register方法:

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    // findSubscriberMethods方法找出一个SubscriberMethod的集合,也就是传进来的订阅者的
    // 所有订阅方法,接下来遍历订阅者的订阅方法来完成订阅者的注册操作。
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

查找订阅者的订阅方法

register方法做了两件事:一件事是查找订阅者的订阅方法,另一件事是订阅者的注册。

在SubscriberMethod类中,主要用来保 存订阅方法的Method对象、线程模式、事件类型、优先级、是否是黏性事件等属性。下面就来查看findSubscriberMethods方法,如下所示:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    // 从缓存中查找是否有订阅方法的集合,如果找到了就立马返回。
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
	// 如果缓存没有,则根据ignoreGeneratedIndex属性的值来选择采用何种方法来查找订阅方法的集合。
    if (ignoreGeneratedIndex) {
        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;
    }
}

ignoreGeneratedIndex 属性表示是否忽略注解器生成的 MyEventBusIndex。

我们在项目中经常通过EventBus单例模式来获取默认的EventBus对 象,也就是ignoreGeneratedIndex为false的情况,这种情况调用了findUsingInfo方法:

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    SubscriberMethodFinder.FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        // 通过 getSubscriberInfo 方法来获取订阅者信息
        findState.subscriberInfo = getSubscriberInfo(findState);
        if (findState.subscriberInfo != null) {
            // 调用subscriberInfo的getSubscriberMethods方法便可以得 到订阅方法相关的信息
            SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
            for (SubscriberMethod subscriberMethod : array) {
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
        } else {
            // 将订阅方法保存到findState中
            findUsingReflectionInSingleClass(findState);
        }
        findState.moveToSuperclass();
    }
    // 回收处理并返回订阅方法的List集合
    return getMethodsAndRelease(findState);
}

默认情况下是没有配置MyEventBusIndex的,因此现在查看一下findUsingReflectionInSingleClass方法的执行过程,如下所示:

private void findUsingReflectionInSingleClass(SubscriberMethodFinder.FindState findState) {
    Method[] methods;
    try {
	   // 通过反射来获取订阅者中所有的方法,并根据方法的类型、参数和注解来找到订阅方法。
        methods = findState.clazz.getDeclaredMethods();
    } catch (Throwable th) {
        methods = findState.clazz.getMethods();
        findState.skipSuperClasses = true;
    }
    for (Method method : methods) {
        int modifiers = method.getModifiers();
        if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
                    Class<?> eventType = parameterTypes[0];
                    if (findState.checkAdd(method, eventType)) {
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        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)) {
            String methodName = method.getDeclaringClass().getName() + "." + method.getName();
            throw new EventBusException(methodName +
                    " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
        }
    }
}

找到订阅方法后将订阅方法的相关信息保存到findState中。

订阅者的注册过程

在查找完订阅者的订阅方法以后便开始对所有的订阅方法进行注册。我们再回到 register方法中,subscribe方法来对订阅方法进行注册,如下所示:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    // 根据subscriber(订阅者)和subscriberMethod(订阅方法)创建一个Subscription(订阅对象)
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    // 根据eventType(事件类型)获取Subscriptions(订阅对象集合)
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    // 如果 Subscriptions为null则重新创建,并将Subscriptions根据eventType保存在subscriptionsByEventType(Map集合)
    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<>();
        subscriptionsByEventType.put(eventType, subscriptions);
    } else {
        // 判断订阅者是否已经被注册
        if (subscriptions.contains(newSubscription)) {
            throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                    + eventType);
        }
    }

    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;
        }
    }
	// 通过 subscriber获取subscribedEvents(事件类型集合)。
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);

    if (subscriberMethod.sticky) {
        if (eventInheritance) {
            // 粘性事件的处理
            Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry<Class<?>, Object> entry : entries) {
                Class<?> candidateEventType = entry.getKey();
                if (eventType.isAssignableFrom(candidateEventType)) {
                    Object stickyEvent = entry.getValue();
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            Object stickyEvent = stickyEvents.get(eventType);
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

subscribe方法主要就是做了两件事:一件事是将Subscriptions根据eventType封装到subscriptionsByEventType

中,将subscribedEvents根据subscriber封装到typesBySubscriber中;第二件事就是对黏性事件的处理。

事件的发送

在获取EventBus对象以后,可以通过post方法来进行对事件的提交。post方法的源码如下所示:

public void post(Object event) {
    // PostingThreadState保存事件队列和线程状态信息
    EventBus.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;
        }
    }
}

首先从PostingThreadState对象中取出事件队列,然后再将当前的事件插入事件队列。最后将队列中的

事件依次交由 postSingleEvent 方法进行处理,并移除该事件。之后查看postSingleEvent方法:

private void postSingleEvent(Object event, EventBus.PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    // eventInheritance表示是否向上查找事件的父类,默认为true
    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));
        }
    }
}

eventInheritance 表示是否向上查找事件的父类,它的默认值为 true,可以通过在EventBusBuilder中进行

配置。当eventInheritance为true时,则通过lookupAllEventTypes找到所有的父类事件并存在List中,然后通过

postSingleEventForEventType方法对事件逐一处理。postSingleEventForEventType方法的源码如下所示:

private boolean postSingleEventForEventType(Object event, EventBus.PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        // 同步取出该事件对应的Subscriptions(订阅对象集合)。
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        // 遍历Subscriptions, 将事件 event 和对应的 Subscription(订阅对象)传递给
        // postingState 并调用postToSubscription方法对事件进 行处理。
        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;
}

接下来查看postToSubscription方法:

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 {
                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(线程模式),之后根据threadMode来分别处理。如果threadMode是

MAIN,若提交事件的线程是主线程,则通过反射直接运行订阅的方法;若其不是主线程,则需要

mainThreadPoster 将我们的订阅事件添加到主线程队列中。mainThreadPoster 是HandlerPoster类型的,继承

自Handler,通过Handler将订阅方法切换到主线程执行。

订阅者取消注册

取消注册则需要调用unregister方法,如下所示:

public synchronized void unregister(Object subscriber) {
    // 通过 subscriber找到subscribedTypes(事件类型集合)。
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        for (Class<?> eventType : subscribedTypes) {
            // 遍历 subscribedTypes,并调用 unsubscribeByEventType方法
            unsubscribeByEventType(subscriber, eventType);
        }
        // 将subscriber对应的eventType从 typesBySubscriber 中移除。
        typesBySubscriber.remove(subscriber);
    } else {
        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

我们在订阅者注册的过程中讲到过typesBySubscriber,它是一个map集合。接下来看unsubscribeByEventType方法:

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--;
            }
        }
    }
}

注释处通过eventType来得到对应的Subscriptions(订阅对象集合),并在for循环中判断如果 Subscription (订阅对象)的subscriber(订阅者)属性等于传进来的subscriber,则从Subscriptions中移除该Subscription。

上一篇:guava EventBus源码阅读


下一篇:细说ReactiveCocoa的冷信号与热信号(一)