当Android项目愈来愈庞大的时候,应用的各个部件之间的通讯变得愈来愈复杂,例如:当某一条件发生时,应用中有几个部件对这个消息感兴趣,那么咱们一般采用的就是观察者模式,使用观察者模式有一个弊病就是部件之间的耦合度过高,在这里将会详细介绍Android中的解耦组件EventBus的使用。html
//定义事件类型: 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个参数是优先级,这两个后面再说。java
在上面这个方法中,使用了一个叫`SubscriberMethodFinder`的类,经过其`findSubscriberMethods`方法找到了一个`SubscriberMethod`列表,前面知道了`SubscriberMethod`表示Subcriber内一个onEvent\*方法,能够看出来`SubscriberMethodFinder`类的做用是在Subscriber中找到全部以methodName(即默认的onEvent)开头的方法,每一个找到的方法被表示为一个`SubscriberMethod`对象。android
`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`的定义:git
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中返回.github
接下来进入第二步,遍历第一步中获得的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`中有这么一段代码:async
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)