Android EventBus源码解析

1.EventBus.getDefault().register(this);

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

首先EventBus.getDefault()通过单例模式和建造者模式创建了一个EventBus对象。

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

这段代码获得订阅者内所有的订阅方法,也就是备注了@Subscribe的方法,返回一个集合。返回的SubscriberMethod对象有以下属性

 	final Method method;//方法
    final ThreadMode threadMode;//回调线程
    final Class<?> eventType;//参数类型
    final int priority;//优先级
    final boolean sticky;//是否是粘性事件
    /** Used for efficient comparison */
    String methodString;//便于比较
synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }

接着上面这一段代码,遍历subscriber内的每一个订阅方法,订阅每一个方法。下面具体看看subscribe()内干了什么,不过在此之前,我们先看EventBus内的几个属性。

	 /**
     * Subscription是一个含有subscriber和subscriberMethod的类
     * eventType是方法的参数类型
     */
    //key是eventType,value是List<Subscription>,也就是通过这个,
    //每一个eventType可以找到其对应的Subscription集合
	private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
	//每一个subscriber找到对应的eventType集合
    private final Map<Object, List<Class<?>>> typesBySubscriber;
    //每一个eventType找到对应的发送的stickyEvent集合
    private final Map<Class<?>, Object> stickyEvents;

subscriber()内第一部分代码

        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> 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;
            }
        }

首先是根据subscriberMethod.eventType,从subscriptionsByEventType获得对应的List
如果为空,说明这个类型的EventType是第一次注册,创建,然后 subscriptionsByEventType.put(eventType, subscriptions),加入集合中。
如果不为空,说明该类型EventType已经注册,并且如果List中已经有相同的subscription对象说明重复注册,抛出异常。
最后根据优先级,将newSubscription插入对应的List,数字大的在前面,如果优先级相同,那么插到后面。
所以第一步是,根据方法的参数类型,从subscriptionsByEventType获得对应的List,然后根据优先级,将subscription插入到指定位置。

第二部分

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

从typesBySubscriber,根据subscriber获得eventType的List。如果为空创建新List,然后插入typesBySubscriber。
最后往List中添加eventType。如果一个订阅者中有多个相同参数的订阅方法,那么List中也会有多个相同的eventType。
所以第二部分是根据subscriber从typesBySubscriber获得对应的eventType的List,然后将eventType加入,可以相同的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);
            }
        }

这一部分是为了支持粘性事件的方法准备的。
首先判断该方法是否支持粘性事件,eventInheritance判断是否传递给父类。

eventType.isAssignableFrom(candidateEventType)

如果eventType是candidateEventType的父类或者相同类型,返回true。也就是说,如果eventInheritance为true,会遍历stickyEvents粘性事件集合,如果某个粘性事件是当前方法的eventType的子类或者相同类型,那么该粘性事件也会发给该方法。
如果eventInheritance是false,stickyEvents.get(eventType),获取当前事件类型的粘性事件,然后发给该方法,与上一步相比就是子类事件不会发过来。
这两部都同样调用了checkPostStickyEventToSubscription()

所以整个subscribe()方法就做了下面这些事:

  1. subscriptionsByEventType<Class eventType,List<subscription>>根据eventType获得对应的List,往里面根据优先插入新的subscription。
  2. typesBySubscriber<Object, List<Class>>根据subscriber获得对应的eventType集合,然后插入新的eventType,可以有相同重复。
  3. 发送粘性事件,如果eventInheritance为true,子类事件也会发送过来。

2.unregister(Object subscriber)

public synchronized void unregister(Object subscriber) {
        List<Class<?>> 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());
        }
    }

首先根据subscriber从typesBySubscriber获得对应的eventType集合。如果为null,说明调用unregister()之前还没有register(),打印警告。
如果不为null,遍历eventType集合,依次调用unsubscribeByEventType(subscriber, eventType)移除subscriptionsByEventType中不需要的元素。最后typesBySubscriber移除对应subscriber。
下面看看怎么移除subscriptionsByEventType中的元素。

2.1unsubscribeByEventType(subscriber, eventType)

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从subscriptionsByEventType获得对应的subscriptions集合,因为subscription含有subscriber和subscriberMethod,所以可能会有subscription有相同的subscriber或subscriberMethod,但不会同时相同。
所以还是要遍历subscriptions集合,如果当前的subscription.subscriber==解绑的subscriber,将该subscription移除。

所以整个unregister()就是移除typesBySubscriber中的subscriber,因为一个subscriber在typesBySubscriber有很多eventType,所以要移除所有的eventType在subscriptionsByEventType中的subscription集合中,subscription.subscriber==当前subscriber的那个subscription

3checkPostStickyEventToSubscription(Subscription newSubscription,Object stickyEvent)

	private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        if (stickyEvent != null) {
            postToSubscription(newSubscription, stickyEvent, isMainThread());
        }
    }

这个在注册时会用到,如果有对应的粘性事件和粘性方法,就会发送。
首先判断粘性事件是否为空,然后调用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);
    }
}

首先是判断调用的subscription.subscriberMethod.threadMode,ThreadMode是一个枚举类型:
POSTING 回调方法的执行线程和发送者所在线程相同
MAIN 回调方法在主线程执行,如果调用者也是主线程直接执行就行;否则加入队列
MAIN_ORDERED 回调方法在主线程执行,但是要先加入队列,等待从队列取出然后在主线程执行
BACKGROUND 回调方法在子线程执行,如果调用者不在主线程,直接在调用者线程执行;否则加入一个后台线程队列等待执行
ASYNC 回调方法在一个子线程执行,这个子线程和调用者线程不同。
其实上面说的加入队列其实是调用不同的Poster.enqueue()方法,至于这些Poster的结构后面再说。

上面的switch分支中,很多都调用了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);
        }
    }

很简单,直接通过反射调用对应的方法。有一点值得注意,这整个postToSubscription()是在注册的时候调用的,如果是一个POSTING方法,如果原本的粘性事件是在子线程发送,那么方法应该也是在相同的线程回调。这是对于先注册,再发送粘性事件的情况,如果先发送粘性事件,再在主线程注册呢?从代码来看应该是在主线程回调,结果也的确是这样。

除了直接在当前线程调用,还有三种情况:
mainThreadPoster
backgroundPoster
asyncPoster
他们都实现了了Poster接口,其中只有一个方法:
void enqueue(Subscription subscription, Object event);
还都实现了Runnable接口

backgroundPoster和asyncPoster

	//backgroundPoster.enqueue()
	public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!executorRunning) {
                executorRunning = true;
                eventBus.getExecutorService().execute(this);
            }
        }
    }

	//asyncPoster.enqueue()
    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        queue.enqueue(pendingPost);
        eventBus.getExecutorService().execute(this);
    }

可以看到,两者类似,不过backgroundPoster只能串行在子线程执行,asyncPoster可以并发执行,两者都是基于线程池执行。前面说了,都实现了Runnable接口,那我们看看这两者的run()方法有何不同

	//backgroundPoster.run()
    public void run() {
        try {
            try {
                while (true) {
                    PendingPost pendingPost = queue.poll(1000);
                    if (pendingPost == null) {
                        synchronized (this) {
                            // Check again, this time in synchronized
                            pendingPost = queue.poll();
                            if (pendingPost == null) {
                                executorRunning = false;
                                return;
                            }
                        }
                    }
                    eventBus.invokeSubscriber(pendingPost);
                }
            } catch (InterruptedException e) {
                eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e);
            }
        } finally {
            executorRunning = false;
        }
    }


	//asyncPoster.run()
    public void run() {
        PendingPost pendingPost = queue.poll();
        if(pendingPost == null) {
            throw new IllegalStateException("No pending post available");
        }
        eventBus.invokeSubscriber(pendingPost);
    }

backgroundPoster通过上锁来保证队列添加取出。asyncPoster则是直接执行。

最后对于mainThreadPoster其实际类型是HandlerPoster,继承了Handler,传入了MainLooper,看看它的enqueue()

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                if (!sendMessage(obtainMessage())) {
                    throw new EventBusException("Could not send handler message");
                }
            }
        }
    }

跟backgroundPoster类似,再看看handleMessage(Message msg)


    @Override
    public void handleMessage(Message msg) {
        boolean rescheduled = false;
        try {
            long started = SystemClock.uptimeMillis();
            while (true) {
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = SystemClock.uptimeMillis() - started;
                if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }

这里

                if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
                }
         ***************
		finally {
            handlerActive = rescheduled;
        }

是为了防止在主线程执行时间过长,如果又一次方法回调时间过长,该方法结束后,先sendMessage()重新触发handleMessage(),然后将handlerActive 赋值为true,表示handler正在处理任务,enqueue()只需要往队列添加任务就行了,不需要再次触发handleMessage()

3.post()

首先看一个EventBus的属性

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

final static class PostingThreadState {
    final List<Object> eventQueue = new ArrayList<>();
    boolean isPosting;
    boolean isMainThread;
    Subscription subscription;
    Object event;
    boolean canceled;
}

这个ThreadLocal记录了每个线程的PostingThreadState,也就是调用post()方法的线程。

    public void post(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> 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,然后向event加入队列,将postingState.isPosting设置为true,在event被真正执行之前,再次调用post()只会将事件加入队列,而不会进行下一步传递。
post()主要是为了保证event被真正执行前,如果多次调用post(),不会重复往下传递事件。因为event需要被传递到真正执行它的地方,而在传递过程中还需要进行许多处理,比如是否需要传递给其父类。

让我们接着来看 postSingleEvent(eventQueue.remove(0), postingState);

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

这一步主要是如果eventInheritance为true,那么会往参数为event父类的方法也回调,然后依次调用postSingleEventForEventType(),如果成功找到了对应的方法,返回true,否则返回false。
如果为false,说明这个类型的event没有方法回调,再根据参数logNoSubscriberMessages决定是否打印结果,sendNoSubscriberEvent 决定是否post一个NoSubscriberEvent事件。

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> 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中根据eventType获得subscriptions集合,前面说过每一个subscription都含有一个subscriber和对应的subscriberMethod。
遍历subscriptions集合,对每一个元素调用postToSubscription(),这个我们之前讲过,在注册时,如果有粘性方法,会通过这个把粘性事件发送。
整个过程就这样结束了,再重新理一下post()流程
post():获得post线程的PostingThreadState,将event加入队列,调用postSingleEvent()

->postSingleEvent():如果需要传递给event父类,找到event所有父类;否则不需要。对每一个eventType调用postSingleEventForEventType(),如果成功回调了方法返回true,否则说明该类参数方法还未注册,根据属性决定是否打印结果和post(NoSubscriberEvent)

->postSingleEventForEventType()根据eventType获得subscriptions集合,遍历调用postToSubscription()

->postToSubscription()根据ThreadMode决定调用。

再看看postSticky

public void postSticky(Object event) {
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event);
    }

跟post()类似,只不过往stickyEvents()加入了当前event()。粘性事件对于已经注册的subscriber和普通事件没有区别,对于新注册的subscriber才会在register()时调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值