EventBus 原理简单记录

这里写图片描述

1、获取 EventBus 对象

EventBus.getDefault()

//单例双重检查方式
public static EventBus getDefault() {  
        if (defaultInstance == null) {  
            synchronized (EventBus.class) {  
                if (defaultInstance == null) {  
                    defaultInstance = new EventBus();  
                }  
            }  
        }  
        return defaultInstance;  
} 

public EventBus() {  
       this(DEFAULT_BUILDER);  
}  

// 建造者模式构造 EventBus
EventBus(EventBusBuilder builder) {  
    subscriptionsByEventType = new HashMap<>();  
    typesBySubscriber = new HashMap<>();  
    stickyEvents = new ConcurrentHashMap<>();  
    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);  
    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、注册订阅者

EventBus.getDefault().register(this)

public void register(Object subscriber) {  
       Class<?> subscriberClass = subscriber.getClass(); 
       //根据订阅者类名来查找订阅者的所有订阅方法 
       List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);  
       synchronized (this) {  
           // 把订阅者和订阅方法注册给事件发送者
           for (SubscriberMethod subscriberMethod : subscriberMethods) {  
               subscribe(subscriber, subscriberMethod);  
           }  
       }  
}

通过 subscriberMethodFinder 根据订阅者类名来查找订阅者的所有订阅方法,然后再把这些方法注册给事件发送者。

SubscriberMethod 类定义如下:

public class SubscriberMethod {  
    final Method method;  
    final ThreadMode threadMode;  
    final Class<?> eventType;  
    final int priority;  
    final boolean sticky;  
    /** Used for efficient comparison */  
    String methodString; 
    //.... 
}

2.1 如何获取订阅者的所有订阅方法信息

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) { 
           //从缓存中获取 
           List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);  
           if (subscriberMethods != null) {  
               return subscriberMethods;  
           }  
           //是否开启订阅者索引优化
           if (ignoreGeneratedIndex) {  
               //使用反射获取
               subscriberMethods = findUsingReflection(subscriberClass);  
           } else {  
               //使用订阅者索引获取
               subscriberMethods = findUsingInfo(subscriberClass);  
           }  
           if (subscriberMethods.isEmpty()) {  
               throw new EventBusException("Subscriber " + subscriberClass+ " and its super classes have no public methods with the @Subscribe annotation");  
           } else {  
               //将获取到的所有方法缓存起来
               METHOD_CACHE.put(subscriberClass, subscriberMethods);  
               return subscriberMethods;  
           }  
}  

2.2 for循环遍历 订阅每个方法

for (SubscriberMethod subscriberMethod : subscriberMethods) {  
      //订阅
      subscribe(subscriber, subscriberMethod);  
}  

订阅方法实现算法
两个 map 来实现存储订阅的信息
key —————- value (list)
事件类型 ——— 订阅信息列表
订阅者 ———— 事件类型列表

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {  
        //获取订阅方法的的订阅事件类型
        Class<?> eventType = subscriberMethod.eventType;  
        //new 一个订阅信息(一个订阅者和它的一个订阅方法)
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);  
        //获取该事件类型的所有订阅信息集合
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);  
        if (subscriptions == null) {  
            subscriptions = new CopyOnWriteArrayList<>();  
            //根据事件类型来存储所有订阅信息(事件 --- 订阅信息)
            //一个EventType可能对应很多个方法和对象,然后就把他们存储起来
            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++) {  
            if (i == size || subscriberMethod.priority >   
                   subscriptions.get(i).subscriberMethod.priority) {  
                //把订阅的这个订阅信息 存储到 该事件类型的 list 中
                subscriptions.add(i, newSubscription);  
                break;  
            }  
        }  

        // 获取该订阅者的订阅事件list
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);  
        if (subscribedEvents == null) {  
            subscribedEvents = new ArrayList<>();  
            // 根据订阅者来存储订阅方法 (订阅者 --- 事件)
            //一个订阅者可能有多个订阅方法,但是每个订阅方法可能会是不同的EventType
            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);  
            }  
        }  
    } 

Subscription 类,封装了订阅者和一个订阅方法

final class Subscription {  
    final Object subscriber;  
    final SubscriberMethod subscriberMethod;  
    /** 
     * Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery 
     * {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions. 
     */  
    volatile boolean active;
    //...
}

3、 发布订阅事件

post(Object event)

public void post(Object event) {  
       PostingThreadState postingState = currentPostingThreadState.get();  
       //拿到发布事件线程的事件队列
       List<Object> eventQueue = postingState.eventQueue;  
       eventQueue.add(event);  

       if (!postingState.isPosting) {  
           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;  
           }  
       }  
} 

PostingThreadState 类

final static class PostingThreadState {  
       final List<Object> eventQueue = new ArrayList<Object>();  
       boolean isPosting;  
       boolean isMainThread;  
       Subscription subscription;  
       Object event;  
       boolean canceled;  
}

postSingleEvent()方法会调用 postSingleEventForEventType()方法来真正地发布事件。

发布步骤是:
1、根据事件类型来获取订阅信息(一个订阅信息存储了一个订阅者和它的一个订阅方法)
2、然后根据订阅信息把事件发布给这些订阅者的订阅方法

postSingleEventForEventType 意为根据事件类型来发布事件,实现如下:

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {  
            CopyOnWriteArrayList<Subscription> subscriptions;  
            synchronized (this) {  
                // 1、根据事件类型来获取订阅信息
                subscriptions = subscriptionsByEventType.get(eventClass);  
            }  
            if (subscriptions != null && !subscriptions.isEmpty()) { 
                // 2、把事件发布给这些订阅者的订阅方法 
                for (Subscription subscription : subscriptions) {  
                    postingState.event = event;  
                    //根据订阅信息来发布事件
                    postingState.subscription = subscription;  
                    boolean aborted = false;  
                    try {  
                        postToSubscription(subscription, event, postingState.isMainThread);  
                        aborted = postingState.canceled;  
                    } finally {  
                        postingState.event = null;  
                        postingState.subscription = null;  
                        postingState.canceled = false;  
                    }  
                    if (aborted) {  
                        break;  
                    }  
                }  
                return true;  
            }  
            return false;  
}  

发布方法 postToSubscription 如下,根据ThreadMode来在不同的线程中发布事件。

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 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);  
       }  
} 

invokeSubscriber 方法如下:

void invokeSubscriber(Subscription subscription, Object event) {  
       try {  
              // 使用反射调用订阅信息保存的订阅方法 
           subscription.subscriberMethod.method.invoke(subscription.subscriber, event);  
       } catch (InvocationTargetException e) {  
           handleSubscriberException(subscription, event, e.getCause());  
       } catch (IllegalAccessException e) {  
           throw new IllegalStateException("Unexpected exception", e);  
       }  
}

我们来看下 backgroundPoster.enqueue(subscription, event); 的 enqueue 方法:

public void enqueue(Subscription subscription, Object event) {  
      PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);  
      synchronized (this) {  
          queue.enqueue(pendingPost);  
          if (!executorRunning) {  
              executorRunning = true;  
              // 交给线程池来执行
              eventBus.getExecutorService().execute(this);  
          }  
      }  
}  

最后线程执行,调用了 backgroundPoster的run方法。

@Override  
public void run() {  
    try {  
        try {  
            while (true) {  
                PendingPost pendingPost = queue.poll(1000);  
                if (pendingPost == null) {  
                    synchronized (this) {  
                        // Check again, this time in synchronized  
                        pendingPost = queue.poll();  
                        if (pendingPost == null) {  
                            executorRunning = false;  
                            return;  
                        }  
                    }  
                }  
                // 最终还是利用反射
                eventBus.invokeSubscriber(pendingPost);  
            }  
        } catch (InterruptedException e) {  
            Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);  
        }  
    } finally {  
        executorRunning = false;  
    }  
} 

简单总结事件能被订阅者接收到的主要步骤:

一、注册订阅者

  1. 获取订阅者的订阅方法
    根据是否开启订阅者索引优化来选择获取订阅方法的策略
    如果开启:使用订阅者索引获取
    如果没有:使用反射
  2. 将获取到的订阅方法注册
    根据 EventType 将对应的订阅方法列表使用 map 保存起来完成注册
    map 结构如下(key – value)
    事件类型 ——— 订阅信息(一个订阅者和它的一个订阅方法)列表

二、post 发布事件

  1. 拿到发布事件线程的事件队列
  2. 往队列里面添加事件
  3. 依次取出队列里面的的事件进行发布
    根据事件的类型来获取对应订阅信息列表
    根据订阅信息使用反射调用订阅方法,并把事件传递给订阅方法

猜你喜欢

转载自blog.csdn.net/iluojie/article/details/80723190