当Android项目越来越庞大的时候,应用的各个部件之间的通信变得越来越复杂,例如:当某一条件发生时,应用中有几个部件对这个消息感兴趣,那么我们通常采用的就是观察者模式,使用观察者模式有一个弊病就是部件之间的耦合度太高,在这里将会详细介绍Android中的解耦组件EventBus的使用。
//定义事件类型: publicclassMyEvent{} //定义事件处理方法: publicvoid onEventMainThread //注册订阅者: EventBus.getDefault().register(this) //发送事件: EventBus.getDefault().post(newMyEvent()) //实现
// EventType -> List<Subscription>,事件到订阅对象之间的映射 privatefinalMap<Class<?>,CopyOnWriteArrayList<Subscription>> subscriptionsByEventType; // Subscriber -> List<EventType>,订阅源到它订阅的的所有事件类型的映射 privatefinalMap<Object,List<Class<?>>> typesBySubscriber; // stickEvent事件,后面会看到 privatefinalMap<Class<?>,Object> stickyEvents; // EventType -> List<? extends EventType>,事件到它的父事件列表的映射。即缓存一个类的所有父类 privatestaticfinalMap<Class<?>,List<Class<?>>> eventTypesCache =newHashMap<Class<?>,List<Class<?>>>();
public void register(Object subscriber) { register(subscriber, defaultMethodName, false, 0); } public void register(Object subscriber, int priority) { register(subscriber, defaultMethodName, false, priority); } public void registerSticky(Object subscriber) { register(subscriber, defaultMethodName, true, 0); } public void registerSticky(Object subscriber, int priority) { register(subscriber, defaultMethodName, true, priority); }
private synchronized void register(Object subscriber, String methodName, boolean sticky, int priority) { List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(), methodName); for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod, sticky, priority); } }
第一个参数就是订阅源,第二个参数就是用到指定方法名约定的,默认为*onEvent*开头,说默认是其实是可以通过参数修改的,但前面说了,方法已被废弃,最好不要用。第三个参数表示是否是*Sticky Event*,第4个参数是优先级,这两个后面再说。
在上面这个方法中,使用了一个叫`SubscriberMethodFinder`的类,通过其`findSubscriberMethods`方法找到了一个`SubscriberMethod`列表,前面知道了`SubscriberMethod`表示Subcriber内一个onEvent\*方法,可以看出来`SubscriberMethodFinder`类的作用是在Subscriber中找到所有以methodName(即默认的onEvent)开头的方法,每个找到的方法被表示为一个`SubscriberMethod`对象。
`SubscriberMethodFinder`就不再分析了,但有两点需要知道:public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List<Object> eventQueue = postingState.eventQueue; eventQueue.add(event); if (postingState.isPosting) { return; } else { 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; } } }
可以看到post内使用了`PostingThreadState`的对象,并且是`ThreadLocal`,来看`PostingThreadState`的定义:
final static class PostingThreadState { List<Object> eventQueue = new ArrayList<Object>(); boolean isPosting; boolean isMainThread; Subscription subscription; Object event; boolean canceled; }
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error { Class<? extends Object> eventClass = event.getClass(); List<Class<?>> eventTypes = findEventTypes(eventClass); // 1 boolean subscriptionFound = false; int countTypes = eventTypes.size(); for (int h = 0; h < countTypes; h++) { // 2 Class<?> clazz = eventTypes.get(h); CopyOnWriteArrayList<Subscription> subscriptions; synchronized (this) { subscriptions = subscriptionsByEventType.get(clazz); } if (subscriptions != null && !subscriptions.isEmpty()) { // 3 for (Subscription subscription : subscriptions) { postingState.event = event; postingState.subscription = subscription; boolean aborted = false; try { postToSubscription(subscription, event, postingState.isMainThread); // 4 aborted = postingState.canceled; } finally { postingState.event = null; postingState.subscription = null; postingState.canceled = false; } if (aborted) { break; } } subscriptionFound = true; } } if (!subscriptionFound) { Log.d(TAG, "No subscribers registered for event " + eventClass); if (eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) { post(new NoSubscriberEvent(this, event)); } } }
来看一下`postSingleEvent`这个函数,首先看第一点,调用了`findEventTypes`这个函数,代码不帖了,这个函数的应用就是,把这个类的类对象、实现的接口及父类的类对象存到一个List中返回.
接下来进入第二步,遍历第一步中得到的List,对List中的每个类对象(即事件类型)执行第三步操作,即找到这个事件类型的所有订阅者向其发送事件。
可以看到,当我们Post一个事件时,这个事件的父事件(事件类的父类的事件)也会被Post,所以如果有个事件订阅者接收Object类型的事件,那么它就可以接收到所有的事件。
还可以看到,实际是通过第四步中的`postToSubscription`来发送事件的,在发送前把事件及订阅者存入了`postingState`中。再来看`postToSubscription`
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { switch (subscription.subscriberMethod.threadMode) { case PostThread: invokeSubscriber(subscription, event); break; case MainThread: if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(subscription, event); } break; case BackgroundThread: 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); } }
这里就用到`ThreadMode`了:
private final PendingPostQueue queue; public void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); synchronized (this) { queue.enqueue(pendingPost); if (!executorRunning) { executorRunning = true; EventBus.executorService.execute(this); } } }
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"); } } } }
public void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); queue.enqueue(pendingPost); EventBus.executorService.execute(this); }
通过`registerSticky`可以注册Stick事件处理函数,前面我们知道了,无论是`register`还是`registerSticky`最后都会调用`Subscribe`函数,在`Subscribe`中有这么一段代码:
if (sticky) { Object stickyEvent; synchronized (stickyEvents) { stickyEvent = stickyEvents.get(eventType); } if (stickyEvent != null) { // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state) // --> Strange corner case, which we don't take care of here. postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper()); } }
也就是会根据事件类型从`stickyEvents`中查找是否有对应的事件,如果有,直接发送这个事件到这个订阅者。
而这个事件是什么时候存起来的呢,同`register`与`registerSticky`一样,和`post`一起的还有一个`postSticky`函数
当通过`postSticky`发送一个事件时,这个类型的事件的最后一次事件会被缓存起来,当有订阅者通过`registerSticky`注册时,会把之前缓存起来的这个事件直接发送给它 。`register`的函数重载中有一个可以指定订阅者的优先级,我们知道`EventBus`中有一个事件类型到List<Subscription>的映射,在这个映射中,所有的Subscription是按priority排序的,这样当post事件时,优先级高的会先得到机会处理事件。
优先级的一个应用就是,高优先级的事件处理函数可以终止事件的传递,通过`cancelEventDelivery`方法,但有一点需要注意,`这个事件的ThreadMode必须是PostThread`,并且只能终止它在处理的事件。
无法进程间通信,如果一个应用内有多个进程的话就没办法了
//注册和发布事件的函数分别为
registerSticky(…)和 postSticky(Object event)