Dispatcher
Dispatcher是guava EventBus的事件分发器.
Dispatcher是抽象类, 抽象方法: abstract void dispatch(Object event, Iterator<Subscriber> subscribers);
定义了3个内部类: ImmediateDispatcher LegacyAsyncDispatcher PerThreadQueuedDispatcher.
这3个类是Dispatcher的实现.
LegacyAsyncDispatcher现在用PerThreadQueuedDispatcher代替
Subscriber包括EventBus, Object target, Method method, Executor executor.
1 final void dispatchEvent(final Object event) { 2 executor.execute(new Runnable() { 3 @Override 4 public void run() { 5 try { 6 invokeSubscriberMethod(event); // 调用method, method.invoke(target, event) 7 } catch (InvocationTargetException e) { 8 bus.handleSubscriberException(e.getCause(), context(event)); 9 } 10 } 11 }); 12 }
Subscriber的dispatchEvent()
1 @Override 2 void dispatch(Object event, Iterator<Subscriber> subscribers) { 3 checkNotNull(event); 4 while (subscribers.hasNext()) { 5 subscribers.next().dispatchEvent(event); 6 } 7 }
ImmediateDispatcher的dispatch()
void dispatch(Object event, Iterator<Subscriber> subscribers) { checkNotNull(event); checkNotNull(subscribers); Queue<Event> queueForThread = queue.get(); // Queues.newArrayDeque() queueForThread.offer(new Event(event, subscribers)); if (!dispatching.get()) { dispatching.set(true); // 是线程安全的 try { Event nextEvent; while ((nextEvent = queueForThread.poll()) != null) { while (nextEvent.subscribers.hasNext()) { nextEvent.subscribers.next().dispatchEvent(nextEvent.event); } } } finally { // 清除 dispatching.remove(); queue.remove(); } } }
1 PerThreadQueuedDispatcher的dispatch() 2 3 PerThreadQueuedDispatcher包括ThreadLocal<Queue<Event>> queue和ThreadLocal<Boolean> dispatching 4 5 dispatching表示是否正在执行dispatch, queue用于让每个线程有一个独立的事件队列.