Android源码学习-EventBus源码浅析

介绍

EventBus是一种用于Android的发布/订阅事件总线。在我们开发中经常将其应用于Activity之间,Fragment之间的通讯传值等。它能达到简化组件间的通信,以及解耦事件的发送者和接受者的作用。

EventBus使用十分简单,在需要发送数据的地方调用post方法,并将数据对象传入

EventBus.getDefault(this).post("test");

​ 在我们期望接受到数据的地方,注册EventBus,并写一个带有@Subscribe注解的方法,该方法只有一个参数,并且其数据类型与post方法发送的数据类型一样。该方法就会接收到post发送的数据。

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
  
        EventBus.getDefault().register(this);
    }
    
    @Subscribe()
    public void receiveValue(String msg){
        
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

源码分析

基于EventBus3.1.1

​ 如上,EventBus有三个关键节点,register注册、post发送和unregister取消注册。这里就根据这三个节点来简单分析下源码。

register注册流程

首先通过getDefault方法获取EventBus单例对象

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

下面是register方法,该方法是注册给定的用来接收事件的subscriber订阅者。

public void register(Object subscriber) {
    Class subscriberClass = subscriber.getClass();
    List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

​ 首先我们看到,调用了subscriber.getClass()方法得到了订阅者的class对象,如上面的例子我们得到的就是Activity的class对象。这里又将这个class对象传到findSubscriberMethods中,findSubscriberMethods的作用是找到订阅者中所有@Subscribe注解标记的方法,将其封装成SubscriberMethod对象并将其添加到集合中返回。

List findSubscriberMethods(Class subscriberClass) {
    List subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }

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

​ 首先会去METHOD_CACHE这个Map中取订阅者的方法集合,如果存在就将其直接返回。如果没有缓存,再去查找。ignoreGeneratedIndex属性值默认为false,这个变量在初始化SubscriberMethodFinder对象时传入

subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
        builder.strictMethodVerification, builder.ignoreGeneratedIndex);

所以,此时执行findUsingInfo方法。

private List 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();
    }
    return getMethodsAndRelease(findState);
}

​ 这里先初始化FindState对象,并调用其initForSubscriber方法为FindStateclazz属性赋值为订阅者的class对象,如下

void initForSubscriber(Class subscriberClass) {
    this.subscriberClass = clazz = subscriberClass;
    skipSuperClasses = false;
    subscriberInfo = null;
}

​ 那么此时while (findState.clazz != null) 判断就成立了,再执行getSubscriberInfo方法获取subscriberInfo

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

​ 上面在initForSubscriber方法中为subscriberInfo赋值为空,而subscriberInfoIndexes属性在实例化SubscriberMethodFinder对象时通过EventBusBuilder对象传入,其值也为空。所以这里的if (findState.subscriberInfo != null)条件不成立,继续执行else分支的findUsingReflectionInSingleClass方法。

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) {
        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");
        }
    }
}

​ 首先获取所有声明在订阅者类中的方法数组methods,然后遍历methods数组,获取方法的修饰符modifiers,判断语句(modifiers & Modifier.PUBLIC) != 0通过修饰符和PUBLIC对应的值进行按位与运算来判断方法的修饰符是否为PUBLIC,不等于0即为PUBLIC;判断语句(modifiers & MODIFIERS_IGNORE) == 0,其中MODIFIERS_IGNORE = Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC;这个MODIFIERS_IGNORE的值与modifiers按位与即判断修饰符是否是MODIFIERS_IGNORE中的任意一个,结果为0即没有这些修饰符。所以经过这个判断,即保证了@Subscribe注解的方法必须是public,非静态以及非抽象的方法。

​ 进入到if 分支,通过getParameterTypes获取到方法的参数类型数组parameterTypes,判断数组长度为1时继续执行,否则抛出异常,也就是这里限制了@Subscribe方法只能有一个参数。然后获取方法上的@Subscribe注解,通过parameterTypes[0]获取到了方法参数的类型eventTypeif (findState.checkAdd(method, eventType))这个判断的checkAdd方法做了两层检查,即判断该方法是否已经添加到集合中了,返回true即没有添加过,继而获取到注解上声明的线程threadMode,并将method方法名、eventType参数类型、threadMode线程、priority优先级、sticky粘性封装成SubscriberMethod对象添加到findState.subscriberMethods集合中。到这里,subscribe方法中findSubscriberMethods查找订阅方法的流程执行结束,并得到了List 格式的集合。遍历前面得到的集合并调用Subscribe方法

// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class eventType = subscriberMethod.eventType;
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
    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;
        }
    }

    List> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);

    if (subscriberMethod.sticky) {
        if (eventInheritance) {
            // 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).
            Set, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry, 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);
        }
    }
}

​ 首先将subscriber订阅者对象和SubscriberMethod订阅方法对象封装成Subscription对象。在该方法中建立了两个Map关联关系,第一个:以事件类型为keyCopyOnWriteArrayListvalue存到subscriptionsByEventType这个Map中,这样就建立了 eventType事件类型和CopyOnWriteArrayList((订阅者对象以及订阅者类中的订阅方法)的对象的集合)。第二个:以订阅者为key,以订阅者类中所有@Subscribe方法的参数类型(即订阅的事件类型)的集合为value存到typesBySubscriber这个Map中。

​ 至此register流程就结束了,这里主要的操作就是找到订阅类中注解为@Subscribe的并且修饰符为public非静态非抽象且只有一个参数的方法,将其封装为SubscriberMethod添加到集合中保存起来。

post发送流程

post方法将给定的event事件发送到Event bus

/** Posts the given event to the event bus. */
public void post(Object event) {
    PostingThreadState postingState = currentPostingThreadState.get();
    List eventQueue = postingState.eventQueue;
    eventQueue.add(event);

    if (!postingState.isPosting) {
        postingState.isMainThread = isMainThread();
        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对象,这个对象中封装了发送相关的状态,如eventQueue为事件集合,这里将event事件添加到这个集合中。判断isPostingfalse表示当前未处于发送状态,再将当前是否处于主线程赋值给isMainThread属性,判断当事件集合不为空时,调用postSingleEvent方法发送集合中的第一个事件。

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) {
        List> 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) {
            logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}

eventInheritance属性代表EventBus是否会考虑event事件的继承结构,当该值为true时发送一个事件,注册了这个事件父类的方法也会收到通知。不管该值为truefalse都会调用到postSingleEventForEventType方法

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
    CopyOnWriteArrayList 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;
}

​ 通过发送的事件类型从subscriptionsByEventType中获取对应的subscriptions集合。遍历subscriptions集合,调用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 MAIN_ORDERED:
            if (mainThreadPoster != null) {
                mainThreadPoster.enqueue(subscription, event);
            } else {
                // temporary: technically not correct as poster not decoupled from subscriber
                invokeSubscriber(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);
    }
}

​ 判断订阅方法指定的执行线程,回调到指定线程中执行订阅方法,即调用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);
    }
}

​ 最后通过反射调用subscriber对象中的method方法,并将event事件传递到方法中,至此post发送流程就结束了。通过Post发送事件的eventType类型从Register流程中构造的subscriptionsByEventType这个Map对象中获取到对应的订阅者以及其中订阅方法的集合,遍历集合再通过反射来执行订阅者中的订阅方法。

unregister取消注册流程

将订阅者从所有事件类中取消注册。

/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
    List> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        for (Class eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        typesBySubscriber.remove(subscriber);
    } else {
        logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

​ 遍历事件类型集合subscribedTypes,调用unsubscribeByEventType方法,并从subscribedTypes移除订阅者subscriber

/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
private void unsubscribeByEventType(Object subscriber, Class eventType) {
    List 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--;
            }
        }
    }
}

​ 根据事件类型获取到subscriptions集合,遍历集合,并将当前订阅者subscriber对应的Subscription对象从集合中移除。取消注册流程比较简单,从typesBySubscriber中移除subscriber,从subscriptions集合中将subscriber对应的Subscription对象移除。

你可能感兴趣的:(Android源码学习-EventBus源码浅析)