EventBus3.1.1 源码解析

前言

在上一文我介绍了EventBus的基础知识以及如何使用EventBus3.0+ 使用入门,但EventBus是如何工作的?还尚且不知,今天就来一探究竟!凡事都有先后顺序,分析代码也一样,我们在使用EventBus的时候一般是按照以下顺序执行:
 1、定义事件
 2、订阅事件
 3、解除订阅
那我也按照这个顺序进行解析。

定义事件

其实这个没什么好分析,简单的讲就是定义一个Bean对象,用来发送所需的数据。

订阅事件

@Override
protected void onCreate(Bundle savedInstanceState) {           
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     // 注册事件
     EventBus.getDefault().register(this);
}

在项目使用中,我们都是在Activty或者Fragmengt的onCreate中通过EventBus.getDefault().register(this)注册事件,那便从getDefault()开始,一探究竟。

1、EventBus#getDefault()

static volatile EventBus defaultInstance;

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

这是我们再熟悉不过的采用双重校验并加锁的单例模式,volatile关键字是为了防止处理器乱序执行而导致DCL(双重校验并加锁)失效的问题。

public EventBus() {
    this(DEFAULT_BUILDER);
}

EventBus(EventBusBuilder builder) {
    logger = builder.getLogger();
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadSupport = builder.getMainThreadSupport();
    mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
    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;
}

在构造方法中主要做了一些变量的初始化。我们还是主要看一下在register中EventBus做了哪些操作。

2、EventBus#register()

public void register(Object subscriber) {
    //  通过我们传入的订阅者对象,获取订阅者class类的实例。
    Class subscriberClass = subscriber.getClass();
    List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

由上述代码可以看出,EventBus通过传入的订阅者实例获取订阅者class类的对象。并通过SubscriberMethodFinder类查找出这个class对象中所有订阅的方法。

3、SubscriberMethodFinder#findSubscriberMethods()

private static final Map, List> METHOD_CACHE = new
            ConcurrentHashMap<>();
            
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是用来缓存订阅方法的,key就是传入的订阅者class类的对象。如果缓存中有则直接获取并返回。
如果是第一次创建,因为EventBus中指定ignoreGeneratedIndex默认为false,则会进入到findUsingInfo()这个方法中。

4、SubscriberMethodFinder#findUsingInfo()

private List findUsingInfo(Class subscriberClass) {
    //  4.1
    FindState findState = prepareFindState();
    //  4.2
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        //  4.3
        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);
        }
        //  4.4 循环查找父类,如果遇到系统类时会跳过,提高查找速度,提升性能
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

其中FindState是一个内部类,用来保存订阅者类相关的信息。

4.1、SubscriberMethodFinder#prepareFindState()
private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];

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

prepareFindState()用来创建FindState对象,首先从FindState池中获取,如果有则直接返回,并且将该下标的对象置空(当获取到订阅方法并且开始发布时又会重新赋值),没有就重新new一个FindState对象。

4.2、SubscriberMethodFinder#FindState#initForSubscriber()
static class FindState {
    final List subscriberMethods = new ArrayList<>();
    final Map anyMethodByEventType = new HashMap<>();
    final Map subscriberClassByMethodKey = new HashMap<>();
    final StringBuilder methodKeyBuilder = new StringBuilder(128);

    Class subscriberClass;
    Class clazz;
    boolean skipSuperClasses;
    SubscriberInfo subscriberInfo;

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

...

}

初始化FindState对象。
 1. subscriberMethods保存SubscriberMethod对象的列表。

4.3、SubscriberMethodFinder#getSubscriberInfo
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;
}

这个方法主要是找到订阅者信息是否存在,如果存在就直接返回,第一次创建返回null。所以上面的findUsingInfo会走到else中,并调用findUsingReflectionInSingleClass()方法。

4.4 SubscriberMethodFinder#FindState#moveToSuperclass()
void moveToSuperclass() {
    if (skipSuperClasses) {
        clazz = null;
    } else {
        clazz = clazz.getSuperclass();
        String clazzName = clazz.getName();
        /** Skip system classes, this just degrades performance. */
        if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName
                .startsWith("android.")) {
            clazz = null;
        }
    }
}

5、SubscriberMethodFinder#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值
        int modifiers = method.getModifiers();
        if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            //  返回方法的参数类型数组
            Class[] parameterTypes = method.getParameterTypes();
            //  如果参数只有1个
            if (parameterTypes.length == 1) {
                //  获取该方法的注解
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                //  如果包含@Subscribe注解
                if (subscribeAnnotation != null) { 
                //  获取订阅方法的事件类型
                Class eventType = parameterTypes[0];
                    if (findState.checkAdd(method, eventType)) {
                        //  获取订阅方法的线程模型
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        //  5.1 保存订阅者信息
                        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对象的subscriberMethods列表中,包括订阅方法、事件类型、线程模型、优先级、粘黏性。

5.1 SubscriberMethod#SubscriberMethod()
public class SubscriberMethod {
    final Method method;
    final ThreadMode threadMode;
    final Class eventType;
    final int priority;
    final boolean sticky;
    /** Used for efficient comparison */
    String methodString;

    public SubscriberMethod(Method method, Class eventType, ThreadMode threadMode, int priority, boolean sticky) {
        this.method = method;
        this.threadMode = threadMode;
        this.eventType = eventType;
        this.priority = priority;
        this.sticky = sticky;
    }
    
    ...
    
}

至此,当findUsingInfo的循环结束时,通过Register()传进来的订阅者类的对象,查找到订阅者类中所有的订阅方法以及相关信息就结束了。

6、SubscriberMethodFinder#getMethodsAndRelease()

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

这个方法的主要作用是对findState做初始化处理,释放内存,将findState保存到FindState池之前被置空的下标中,方便下一次使用。然后返回SubscriberMethod对象列表,保存到METHOD_CACHE中。

7、EventBus#subscribe()

public void register(Object subscriber) {
    Class subscriberClass = subscriber.getClass();
    List 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对象
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
    //  1. 如果 subscriptionsByEventType 中没有以该事件类型作为key值的存在,则添加。
    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++) {
        //  按照优先级添加,等级越高在List中位置越靠前
        if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
            subscriptions.add(i, newSubscription);
            break;
        }
    }
        
    //  2. 将订阅者类中所有的事件类型保存在map中,订阅者类的对象作为key值,事件类型列表作为value。
    List> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);
        
    //  3. 判断是否是粘性事件
    if (subscriberMethod.sticky) {
        //  默认为true
        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);
        }
    }
}

我们把焦点再次聚焦到register()方法中,当EventBus找到订阅者类中所有的订阅方法时,会调用subscribe()方法。在subscribe()方法中主要有三个部分,分别对应三个if判断,在上面代码中都有一一讲解。

EventBus的事件订阅到此就分析结束了,接下来要讲的是事件的发布,它是怎么发布事件的?又是怎么切换线程的?

8、EventBus#post()

public void post(Object event) {
    //  获取PostingThreadState对象
    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,然后把当前事件添加到事件队列中,如果当前事件没有处在发布状态,在则会进入到if判断中,最终会调用postSingleEvent()方法,并且通过eventQueue.remove(0)删除已经发布的事件。

9、EventBus#postSingleEvent()

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    //  获取事件类的Class类型
    Class eventClass = event.getClass();
    boolean subscriptionFound = false;
    //  默认为true
    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));
        }
    }
}
9.1、EventBus#lookupAllEventTypes()
private static List> lookupAllEventTypes(Class eventClass) {
    synchronized (eventTypesCache) {
        //  获取和这个事件类相关的class列表(包括父类和接口)
        List> eventTypes = eventTypesCache.get(eventClass);
        if (eventTypes == null) {
            eventTypes = new ArrayList<>();
            Class clazz = eventClass;
            //  循环添加这个事件类的父类和接口,并作为事件保存和发送
            while (clazz != null) {
                eventTypes.add(clazz);
                addInterfaces(eventTypes, clazz.getInterfaces());
                clazz = clazz.getSuperclass();
            }
            eventTypesCache.put(eventClass, eventTypes);
        }
        return eventTypes;
    }
}

这个方法主要是获取Event事件类及其父类和接口的所有class列表,并以key/value的形式添加到eventTypesCache这个缓存对象性中,方便下次直接使用,提升性能。

10、EventBus#postSingleEventForEventType()

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
    CopyOnWriteArrayList subscriptions;
    synchronized (this) {
        //  根据事件类型获取对应Subscription列表
        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;
}

postSingleEventForEventType()方法主要是获取订阅了该事件类型的所有的Subscription列表,然后遍历列表对里面的每个对象调用postToSubscription()方法。

11、EventBus#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);
    }
}

到了这里EventBus的事件发布解析就结束了。在这个方法中首先获取当前事件的订阅方法的线程模型,然后根据线程模型选择对应的线程去完成事件的发布。invokeSubscriber()主要是利用反射去调用方法,这样就实现了订阅事件->发布事件->接收事件这一过程。

12、EventBus#unregister()

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

这里主要是把订阅者传进去,得到当前订阅者订阅的所有的事件列表,遍历是列表移除与订阅者相关的所有信息。

12.1、EventBus#unsubscribeByEventType()
private void unsubscribeByEventType(Object subscriber, Class eventType) {
    //  获取事件类型对应的Subscription集合
    List subscriptions = subscriptionsByEventType.get(eventType);
    if (subscriptions != null) {
        int size = subscriptions.size();
        //  遍历subscriptions列表,移除所有信息
        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的分析就全部结束了,核心部分集中在订阅和发布。订阅主要是为了找到所有的订阅方法和事件并保存相互关联的信息,发布主要是从保存的相互关联的信息当中找到以被发布的事件类型作为参数的所有订阅方法并通过反射调用该方法。

你可能感兴趣的:(EventBus3.1.1 源码解析)