EventBus源码分析

最近在学习Rxjava,它的思想让我回想起了之前项目中用到的EventBus,事件订阅。但EventBus的具体原理己经记不清,就跑回去看了下它的源码。今天总结下。它的使用方法很简单,不知道如何使用的可以看看我之前写过的一篇博客[不可不知的EventBus]。(http://blog.csdn.net/u014486880/article/details/48449907)

使用差别

在这里还是要说一下,这里分析的是EventBus3.0的源码,3.0的用法跟2.2的用法有点区别,但区别也不大,只是把处理方法换成了注解的形式。如下:

public void onEventMainThread(Event event) {    
    }   

换成了:

@Subscribe(threadMode = ThreadMode.MainThread) //在ui线程执行
    public void onUserEvent(UserEvent event) {
    }

不再需要使得具体的使用就不再详细说了。

EventBus源码

register

入口当然是EventBus.getDefault().register(this),先看下getDefault()。

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

可见它其实是一个标准的单例模式。再看下register方法:

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

SubscriberMethodFinder类就是用来查找和缓存订阅者响应函数的信息的类。那怎么才能获得订阅者响应函数的相关信息呢。本博客是基于3.0版本的,在3.0版本中,EventBus提供了一个EventBusAnnotationProcessor注解处理器来在编译期通过读取@Subscribe()注解并解析,处理其中所包含的信息,然后生成java类来保存所有订阅者关于订阅的信息,这样就比在运行时使用反射来获得这些订阅者的信息速度要快。来看下findSubscriberMethods怎么执行的:

List  findSubscriberMethods(Class subscriberClass) {
    List subscriberMethods = METHOD_CACHE.get(subscriberClass); //如有缓存存在
    if (subscriberMethods != null) {
        return subscriberMethods;
    }

    if (ignoreGeneratedIndex) {
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        subscriberMethods = findUsingInfo(subscriberClass);///从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
    }
    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 ;
    }
}

首先判断缓存中有没有存在,存在就直接加载,不存在就通过findUsingReflection或者findUsingInfo来进行方法的查找。findUsingReflection是用反射来查找注解@Subscribe从而获取到订阅方法,findUsingInfo是从从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息。这里只分析findUsingReflection的具体流程:

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

主要流程在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") ;
        }
    }
}

就开始遍历每一个方法了,去匹配封装了。反射读取注解,将method, threadMode, eventType传入构造了:new SubscriberMethod(method, threadMode, eventType)。添加到List。
看下继续往下看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;
        }
    }
}

可以看到,会扫描所有的父类,不仅仅是当前类。
上面说了这么多,其实只要记住一句话:扫描了所有的方法,把匹配的方法最终保存起来。
回到register方法,继续往来就来到subscribe()方法啦,将上面找到的subscriberMethods这个list传入 :

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);
        }
    }
// //根据优先级priority来添加Subscription对象
    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;
        }
    }
//将订阅者对象以及订阅的事件保存到typesBySubscriber里
    List> subscribedEvents = typesBySubscriber .get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber .put(subscriber, subscribedEvents) ;
    }
    subscribedEvents.add(eventType);
//如果接收sticky事件,立即分发sticky事件
    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);
        }
    }
}

上面代码其实也很好理解,首先得到事件类型的所有订阅信息,根据优先级将当前订阅信息插入到订阅者队列subscriptionsByEventType中,得到有序的队列后,就将其放到typesBySubscriber 中。最后判断是否设置了接收sticky事件,如果接收sticky事件,取出sticky事件消息发送给订阅者。

post

分析完register后,就要看看post,是如何分发事件的。
在看源码之前,我们猜测下:register时,把方法存在subscriptionsByEventType;那么post肯定会去subscriptionsByEventType去取,然后调用。

public void post(Object event) {
    PostingThreadState postingState = currentPostingThreadState .get();
    List 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;
        }
    }
}
 
  

首先通过currentPostingThreadState.get()来得到当前线程PostingThreadState的对象:

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

接着将Post的参数对象入队列,判断队列里是否为空,如果不为空,一直发送。发送调用的是postSingleEvent。

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class eventClass = event.getClass();
    boolean subscriptionFound = false;
    if ( eventInheritance) {
//查找eventClass类所有的父类以及接口
        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) {
            Log.d (TAG, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent. class &&
                eventClass != SubscriberExceptionEvent. class) {
            post(new NoSubscriberEvent(this, event)) ;
        }
    }
}

判断事件是否可以继承,如果可以就查找eventClass所有父类及接口,获得订阅了该事件的所有订阅都后,调用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中对象,并调用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) ;
    }
}

实际上就是通过反射调用了订阅者的订阅函数并把event传入。
总结上面的代码就是,首先从currentPostingThreadState获取当前线程信息,在subscriptionsByEventType里获得所有订阅了这个事件的Subscription列表,然后在通过postToSubscription()方法来分发事件,在postToSubscription()通过不同的threadMode在不同的线程里invoke()订阅者的方法,ThreadMode共有四类:

  • PostThread:默认的 ThreadMode,表示在执行 Post 操作的线程直接调用订阅者的事件响应方法,不论该线程是否为主线程(UI 线程)。当该线程为主线程时,响应方法中不能有耗时操作,否则有卡主线程的风险。它不能耗时的操作;
  • MainThread:在主线程中执行响应方法。如果发布线程就是主线程,则直接调用订阅者的事件响应方法,否则通过主线程的 Handler 发送消息在主线程中处理——调用订阅者的事件响应函数。显然,MainThread类的方法也不能有耗时操作,以避免卡主线程。
  • BackgroundThread:在后台线程中执行响应方法。如果发布线程不是主线程,则直接调用订阅者的事件响应函数,否则启动唯一的后台线程去处理。由于后台线程是唯一的,当事件超过一个的时候,它们会被放在队列中依次执行,因此该类响应方法虽然没有PostThread类和MainThread类方法对性能敏感,但最好不要有重度耗时的操作或太频繁的轻度耗时操作,以造成其他操作等待。适用场景:操作轻微耗时且不会过于频繁,即一般的耗时操作都可以放在这里;
  • Async:不论发布线程是否为主线程,都使用一个空闲线程来处理。和BackgroundThread不同的是,Async类的所有线程是相互独立的,因此不会出现卡线程的问题。适用场景:长耗时操作,例如网络访问。
    以上就是几中适用场景。要根据自己的业务需求进行选择。

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 {
        Log.w( TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

最终分别从typesBySubscriber和subscriptions里分别移除订阅者以及相关信息即可。获到取typesBySubscriber 中要删除的对象,并进行remove。看下unsubscribeByEventType方法:

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

好啦,EventBus的简单源码分析就分析到这吧。

你可能感兴趣的:(android,android技术分享与探讨,android源码分析)