EventBus 简单源码、原理分析
2018-02-24 15:51
316 查看
1.初始化
传入一个默认builder 进行初始化
2.注册、取消注册
subscriptionsByEventType 键 eventType(事件类型) 值 所有注册过该事件的对象 读写分离cow list
typesBySubscriber 键 注册对象 值 对象下所有注册事件
stickyEvents sticky事件存储
取消注册
subscriptionsByEventType typesBySubscriber 将注册的全部事件从两个map中删除。
3.post
最后通过该方法完成发送
EventBus.getDefatult(),单例模式初始化。
public static EventBus getDefault() { EventBus instance = defaultInstance; if (instance == null) { synchronized (EventBus.class) { instance = EventBus.defaultInstance; if (instance == null) { instance = EventBus.defaultInstance = new EventBus(); } } } return instance; }
传入一个默认builder 进行初始化
public EventBus() { this(DEFAULT_BUILDER); } EventBus(EventBusBuilder builder) { logger = builder.getLogger(); subscriptionsByEventType = new HashMap<>(); typesBySubscriber = new HashMap<>(); stickyEvents = new ConcurrentHashMap<>(); mainThreadSupport = builder.getMainThreadSupport(); mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null; backgroundPoster = new BackgroundPoster(this); asyncPoster = new AsyncPoster(this); indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0; subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes, builder.strictMethodVerification, builder.ignoreGeneratedIndex); logSubscriberExceptions = builder.logSubscriberExceptions; logNoSubscriberMessages = builder.logNoSubscriberMessages; sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent; sendNoSubscriberEvent = builder.sendNoSubscriberEvent; throwSubscriberException = builder.throwSubscriberException; eventInheritance = builder.eventInheritance; executorService = builder.executorService; }
2.注册、取消注册
通过subscriberMenthodFinder找到所有类 父类中的@Subscriber的方法。
public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass();//传入activity fragment List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } } }
subscriptionsByEventType 键 eventType(事件类型) 值 所有注册过该事件的对象 读写分离cow list
typesBySubscriber 键 注册对象 值 对象下所有注册事件
stickyEvents sticky事件存储
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { Class<?> eventType = subscriberMethod.eventType;//获取class Subscription newSubscription = new Subscription(subscriber, subscriberMethod);//将一个方法封装成对象 CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);//获取存储subscription的cowList if (subscriptions == null) {//如果为null new对象 put到subscriptionsByEventType(map) subscriptions = new CopyOnWriteArrayList<>(); subscriptionsByEventType.put(eventType, subscriptions); } else { if (subscriptions.contains(newSubscription)) {//是否包含 包含为重复注册 throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType); } } int size = subscriptions.size(); for (int i = 0; i <= size; i++) {//判断当前优先级 如大于则插入subscriptions() if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) { subscriptions.add(i, newSubscription); break; } }
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); if (subscriberMethod.sticky) { if (eventInheritance) { // Existing sticky events of all subclasses of eventType have to be considered. // Note: Iterating over all events may be inefficient with lots of sticky events, // thus data structure should be changed to allow a more efficient lookup // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>). Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet(); for (Map.Entry<Class<?>, Object> entry : entries) { Class<?> candidateEventType = entry.getKey(); if (eventType.isAssignableFrom(candidateEventType)) { Object stickyEvent = entry.getValue(); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } } else { Object stickyEvent = stickyEvents.get(eventType); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } }
取消注册
subscriptionsByEventType typesBySubscriber 将注册的全部事件从两个map中删除。
public synchronized void unregister(Object subscriber) { List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber); if (subscribedTypes != null) { for (Class<?> eventType : subscribedTypes) { unsubscribeByEventType(subscriber, eventType); } typesBySubscriber.remove(subscriber); } else { logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass()); } }
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) { List<Subscription> subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions != null) { int size = subscriptions.size(); for (int i = 0; i < size; i++) { Subscription subscription = subscriptions.get(i); if (subscription.subscriber == subscriber) {//获取全部该eventType 移除当前取消注册对象 subscription.active = false; subscriptions.remove(i); i--; size--; } } } }
3.post
public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List<Object> eventQueue = postingState.eventQueue; eventQueue.add(event); if (!postingState.isPosting) { postingState.isMainThread = isMainThread(); 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; } } }
最后通过该方法完成发送
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { switch (subscription.subscriberMethod.threadMode) { case POSTING: invokeSubscriber(subscription, event); break; case MAIN: if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(subscription, event); } break; case MAIN_ORDERED: if (mainThreadPoster != null) { mainThreadPoster.enqueue(subscription, event); } else { // temporary: technically not correct as poster not decoupled from subscriber invokeSubscriber(subscription, event); } break; case BACKGROUND: 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); } }
相关文章推荐
- springmvc源码分析原理及简单实现
- EventBus原理源码分析和使用
- Linux网络编程【四】:进程池、线程池原理及简单线程池源码分析
- 一个简单的示例讲解游戏游戏编程原理。附示例源码
- softirq原理以及源码分析
- tasklet原理和源码分析
- Spring3.0核心组件的源码简单分析
- discuz 1.5X源码简单分析
- Java中HashMap底层实现原理(JDK1.8)源码分析
- 利用JAVA的动态属性之反射原理实现一个简单AOP容器 - AOP的实现原理分析
- 等待队列的原理与源码分析
- SpringMVC关于json、xml自动转换的原理研究[附带源码分析 --转
- Kinect v2控制鼠标原理分析和源码(0积分下载)
- handler运行原理源码分析
- spark机器学习 源码解析及原理分析
- jQuery-1.9.1源码分析系列(三) Sizzle选择器引擎——编译原理
- google probuf反射原理之源码分析
- Spark2.2 job触发流程原理剖析与源码分析
- ReentrantLock可重入锁的理解和源码简单分析
- Spark streaming源码分析之Job动态生成原理与源码解析