Guava EventBus组件
// Class is typically registered by the container. class EventBusChangeRecorder { @Subscribe public void recordCustomerChange(ChangeEvent e) { recordChange(e.getChange()); } } // somewhere during initialization eventBus.register(new EventBusChangeRecorder()); // much later public void changeCustomer() { ChangeEvent event = getChangeEvent(); eventBus.post(event); }
使用方式,定义evenBus实例,经过register方法将须要调用的组件注册到eventBus中,而后使用eventBus.post(event)方式实现组件交互,event 问一个时间参数,能够理解为,上列中EventBusChangeRecord.recordCustomerChange 的ChangeEvent 参数。
官网文档:数组
EventBus allows publish-subscribe-style communication between components without requiring the components to explicitly register with one another (and thus be aware of each other). It is designed exclusively to replace traditional Java in-process event distribution using explicit registration. It is not a general-purpose publish-subscribe system, nor is it intended for interprocess communication.并发
@Subscribe 定义当调用eventBus.post时,使用EventBusChangeRecorder中的哪一个方法进行相应。
EventBus内部机制:
调用EventBus.register : 将须要调用的组件传入,如上列中的EventBusChangeRecorder对象实例,EventBus会经过反射以及上面的@Subscribe注释,获得一个SetMultiMap<Class<?> , EventHandler> 的集合。简单说就是找出须要调用组件的哪一个方法,如recordCustomerChange(ChangeEvent e)
须要注意的是,经过这个方法要求传入的组件的接口方法有且只能有一个参数。
调用EventBus 的 post(Object event)方法 : 这里面有两部,找到任何可能的方法和参数组合将组合放到一个ConcurrentLinkedQueue<EventWithHandler>中,而后循环从Queue中拿出EventWithHandler 进行调用。
就这么简单~~ , 这全部的事情是在一个线程中完成的,只是EvenBus 为它的成员变量使用了 ThreadLocal 保证线程并发下的问题。