static { // Version 0.1 def stickyEvents = new ConcurrentHashMap<Class, Object>() com.google.common.eventbus.EventBus.metaClass.registerSticky = { object -> Multimap<Class, ?> methodsInListener = delegate.finder.findAllSubscribers(object) delegate.subscribersByTypeLock.writeLock().lock() try { delegate.subscribersByType.putAll(methodsInListener) // dispatch sticky events methodsInListener.entries().each { e1 -> Class eventType = e1.key def wrapper = e1.value stickyEvents.entrySet().each { entry -> Class candidateEventType = entry.key if (eventType.isAssignableFrom(candidateEventType)) { def stickyEvent = entry.getValue() // println("sticky Dispatch $candidateEventType Want: $eventType $wrapper $stickyEvent") delegate.enqueueEvent(stickyEvent, wrapper) } } } } finally { delegate.subscribersByTypeLock.writeLock().unlock() } delegate.dispatchQueuedEvents() } com.google.common.eventbus.EventBus.metaClass.postSticky = { event -> synchronized (stickyEvents) { stickyEvents.put(event.class, event) } delegate.post(event) } }
已知BUG:stickyEvents是全局的,实际上每个EventBus需要独立的stickyEvents。由于项目中只需要EventBus单例,同时也没有特别好的解决方法,暂时先这样。
原则No.1:代码美观
时间: 2024-10-13 03:42:17