EventBus源码分析

EventBus

EventBus是一个为Android和Java平台设计的发布/订阅事件总线

EventBus源码分析_第1张图片
image

EventBus有以下特点:

  • 简化组件之间的通信
    • 将事件发送方和事件接收方解耦
    • 很好的使用于ActivitisFragments后台线程
    • 避免复杂、易出错的依赖
  • 简化你的代码
  • 体积小(~50K jar)
  • 有100,000,000+次相关APP安装,证明EventBus的可靠性
  • 还有其他额外的功能

集成到项目

gradle配置:

implementation 'org.greenrobot:eventbus:3.1.1'

使用(只需3步)

  1. 定义事件

    public static class MessageEvent { /* 如果有需要,可以声明相应的属性 */ }

  2. 声明订阅方法

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {/* Do something */};

需要@Subscribe注解,默认的threadModeThreadMode.MAIN

注册反注册订阅,比如在ActivitiesFragments中根据生命周期方法去注册和反注册

@Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }
  1. 发送事件

    EventBus.getDefault().post(new MessageEvent());

源码解析

register

/**
 * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
 * are no longer interested in receiving events.
 * 

* Subscribers have event handling methods that must be annotated by {@link Subscribe}. * The {@link Subscribe} annotation also allows configuration like {@link * ThreadMode} and priority. */ public void register(Object subscriber) { Class subscriberClass = subscriber.getClass(); List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);// -> 1 synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod);// -> 2 } } }

注释:
注册subscriber用来接收事件,当不再希望接收到事件发送时必须要调用unregister取消注册
subscriber必须包含带Subscribe注解的方法,Subscribe注解可配置ThreadModepriority

  • 注释1处代码:

    List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

根据sbuscriber的class去查找带有@subscribe注解的方法,findSubscriberMethods方法:

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

    if (ignoreGeneratedIndex) {// -> 4
        subscriberMethods = findUsingReflection(subscriberClass);// -> 5
    } else {
        subscriberMethods = findUsingInfo(subscriberClass);// -> 6
    }
    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;
    }
}
  • 注释3处代码

先从缓存中去查找该subscriber中订阅的方法,如果查到,直接返回。
METHOD_CACHE缓存中的数据是在register后添加的,但是unregister的时候并不会清掉,这样当一个subscriber注册完,然后反注册,下次再注册的时候,不需要再去查找其中订阅的方法。

  • 注释4处的代码

如果上一步没有查到相应的方法,就会走到这一步,先根据ignoreGeneratedIndex判断是否忽略索引查找,如果忽略,则执行注释5处的代码,不管你是否添加了index所有,都利用反射去查找subscriber中订阅的方法列表;如果不忽略,则执行6处的代码,先从索引index中去查找,如果没有索引或者索引中没有找到,再考虑利用反射的方式去查找。
关于索引index的使用后面会提到。

  • 注释5处的代码

调用findUsingReflection方法:

private List findUsingReflection(Class subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {// -> 7
        findUsingReflectionInSingleClass(findState);// -> 8
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}


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");
        }
    }
}
  • 注释7处的代码

这里之所以使用while循环而不用if判断,是因为除了查找当前subscriber还需要查找其向上的继承链,findState.moveToSuperclass();就是用来控制向上查找的,EventBus中所有的继承链查找都是用这种方式,不要迷惑就好。

  • 注释8处的代码

这里就是调用了findUsingReflectionInSingleClass去用反射的方式查找subscriber中订阅的方法列表,代码很简单,就是普通的反射使用,看不懂的问我吧。

反射的逻辑就这些

再回到注释4处的代码继续分析另外一种查找方法列表的方式:

  • 注释6处的代码

调用findUsingInfo方法:

private List findUsingInfo(Class subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        findState.subscriberInfo = getSubscriberInfo(findState);// -> 9
        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);// -> 10
        }
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}
  • 注释9处代码

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

这里有两个分支,第一次register的时候,第一个分支条件是不会成立的,我们看第二个分支:

这里的subscriberInfoIndexes就是我们通过EventBus的注解生成的index索引,然后调用EventBus.builder().addIndex(new MyEventBusIndex()).build();添加的,这个索引的作用就是把本来运行时通过反射查找订阅方法的逻辑换成了编译器自动生成文件,然后运行时在该文件中直接去查找的方式,从而提高了效率,index索引的方式后面会介绍。

  • 注释10处的代码

如果我们没有添加index索引,那么代码9处得到的findState.subscriberInfo就是null,代码就会走到注释10处,注释10处的逻辑和上面注释8处的逻辑一样,都是通过反射去查找订阅方法。

到这里,不管通过哪种方式,订阅的方法列表已经找到了,我们回到注释1处接着往下看:

  • 注释2处的代码:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //获取事件类型
    Class eventType = subscriberMethod.eventType;
    // 将订阅者和订阅者中的订阅方法打包成一个Subscription对象
    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();
    // 遍历订阅了该event类型的方法,根据priority把新订阅的方法放到合适的位置
    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);
        }
    }
}

至此,register流程已经走完。

post事件流程

post事件的流程很简单,就是通过反射调用相应的方法(订阅的方法在上一步已经找到并存到了相应的集合中)即可。

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);// -> 1
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

  • 注释1处代码

调用postSingleEvent方法:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) { // -> 2
        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); // -> 3
        }
    } else {
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass); // -> 4
    }
    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));
        }
    }
}
  • 注释2处代码

eventInheritance:该属性可以在EventBus的Build中初始化,默认是true。

true的情况举个例子:
A和B是两个Event,并且A extends B
X和Y是两个方法,X订阅了事件A,Y订阅了事件B
post A事件,同时会post B事件,那么X和Y都会收到事件

fasle的情况就是:post哪个事件,就只会发送这一个事件,不会发送它的父类事件,上面这个例子,如果eventInheritance为false,post A的时候Y就不会收到事件

  • 注释3和注释4代码

都调用了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);// -> 5
                aborted = postingState.canceled;
            } finally {
                postingState.event = null;
                postingState.subscription = null;
                postingState.canceled = false;
            }
            if (aborted) {
                break;
            }
        }
        return true;
    }
    return false;
}
  • 注释5处代码:

这里就是遍历到该event中的所有订阅方法,挨个给他们发送事件,具体的发送逻辑就是代码5处的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:// 没太看懂和MAIN有啥区别
            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);
    }
}

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

这里就是根据不同的ThreadMode去执行不同的逻辑了,invokeSubscriber就是通过反射的方式去调用方法,没什么可说的。

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

unregister的时候,会把该subscriber中的订阅方法都从集合中移除掉,同时也会把该subscriber从相应的集合中移除掉。

索引index

EventBus提供一个注解处理器,可以在编译期把你项目中所有regisger的class和所有的 @Subscribe 方法给整合起来,生成一个特殊的类,类似下面:

/** This class is generated by EventBus, do not edit. */
public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap, SubscriberInfo>();// key就是register的对象, value就是该对象中@subscribe的方法集合

        putIndex(new SimpleSubscriberInfo(cn.jerry.webviewdemo.FirstActivity.class, true, new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onEventArrived", cn.jerry.webviewdemo.CustomEvent.class),
        }));

    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    // 根据class对象获取该对象中@Subscribe注解的方法列表
    public SubscriberInfo getSubscriberInfo(Class subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}

代码运行的时候,再遇到register逻辑,会直接从这个索引中查找相应的方法列表,从而避免了相应的反射操作,上面提到的register流程的注释9处:

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;
        }
    }
    // 这里就是从刚刚的index处去查找
    if (subscriberInfoIndexes != null) {
        for (SubscriberInfoIndex index : subscriberInfoIndexes) {
            // 根据相应的class对象,去查找该对象中@subscribe的方法列表
            SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
            if (info != null) {
                return info;
            }
        }
    }
    return null;
}

你可能感兴趣的:(EventBus源码分析)