撸EventBus源码

源码是eventbus-3.1.1

代码入口:

  • EventBus.getDefault().register(Object subscriber)注册订阅者
  • EventBus.getDefault().unregister(Object subscriber)注销订阅者
  • EventBus.getDefault().post(Object event)发送事件
  • @Subscribe()订阅者

创建EventBus

EventBus.getDefault().register(Object subscriber)可以看到EventBus的使用是单例模式:

static volatile EventBus defaultInstance;

public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
}

DCL的单例模式为什么静态变量instance要使用volatile标签?

查看new EventBus()

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

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

这里在new EventBus的时候又使用了构造者模式。
EventBus中几个主要的成员变量:

  • Map, CopyOnWriteArrayList> subscriptionsByEventType
    这个subscriptionsByEventType的key是事件类,value是订阅者list,其中list使用的线程安全的CopyOnWriteArrayList。
  • Map>> typesBySubscriber
    这个typesBySubscriber的key为订阅者,value为订阅者的事件list
  • Map, Object> stickyEvents
    这个stickyEvents为粘性事件,key为事件的类,value为事件对象

注册

public void register(Object subscriber) {
    //获取订阅者类名
    Class subscriberClass = subscriber.getClass();
    // 1   获取订阅者订阅的方法   
    List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
    // 2  在同步块中将订阅方法进行注册
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

一般情况下register的入参是Activity、Service、Fragment这个有生命周期的对象,所有在对象的生命周期开始的地方进行注册,并在生命周期结束的时候进行注销。

看标注1处,这里使用subscriberMethodFinder的findSubscriberMethods()方法获取订阅者的订阅方法:

List findSubscriberMethods(Class subscriberClass) {
    List 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;
    }
}

可以看到方法中先查看缓存中是否存在此订阅者的订阅方法,如果没有就通过findUsingInfo()进行查找,然后将查找到的结果放入缓存,并返回结果。

private List findUsingInfo(Class subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        findState.subscriberInfo = getSubscriberInfo(findState);
        if (findState.subscriberInfo != null) {
            SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
            for (SubscriberMethod subscriberMethod : array) {
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
        } else {
            findUsingReflectionInSingleClass(findState);
        }
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

这里通过findUsingReflectionInSingleClass(findState);方法进行查找订阅方法,查找完成后会继续查找订阅者类的父类的订阅方法,直到当前查找的类是系统类时跳出循环。

    private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // This is faster than getMethods, especially when subscribers are fat classes like Activities
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
        for (Method method : methods) {
            int modifiers = method.getModifiers();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 1) {
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        Class eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    }
                } 
                ...
        }
    }

从名字就可以看出是通过反射的方法进行查找,在查找的过程中通过遍历每个订阅者类的每个方法的注解,如有存在@Subscribe()则表明是订阅方法,并将这个method的注解参数进行解析,最终一并加入list中。

至此,注册的第一步完成:获取订阅者类的订阅方法(因为方法可能多个,所有用list)。再看注册的第二部分:

        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }

主要看subscribe(subscriber, subscriberMethod)方法。

    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //获取这个订阅方法中订阅的事件(订阅方法的入参)
        Class eventType = subscriberMethod.eventType;
        //通过订阅类和订阅方法注册一个订阅对象Subscription
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        /**
         * 获取订阅当前事件的所有订阅对象,
         * 如果为空那就创建一个list用于存储,并将这个list放入subscriptionsByEventType中
         **/
        CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } 
        // 按优先级顺序插入当前的订阅对象
        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }
        //将当前订阅类作为key,订阅事件作为value传入typesBySubscriber中
        List> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        //POST粘性事件
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
            //  包含事件父类的情况(默认true)
                // 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).
                Set, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry, 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);
            }
        }
    }

至此,订阅的注册完成,在完成注册的时候会将订阅的类、订阅的方法、订阅的事件统一存到EventBus对象中,为后面事件的发送进行处理;粘性事件会在订阅的类注册完成的时候触发订阅方法


注销

    public synchronized void unregister(Object subscriber) {
        // 1 根据订阅类获取订阅事件
        List> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class eventType : subscribedTypes) {
                // 2 解除订阅事件和订阅类的绑定关系
                unsubscribeByEventType(subscriber, eventType);
            }
            // 3 移除订阅类
            typesBySubscriber.remove(subscriber);
        } 
        ...
    }

注销方法中第一个注释的地方是通过订阅类获取订阅事件,然后对每一个订阅事件解除与订阅类的关系,最后移除订阅类。

解除订阅事件和订阅类的绑定关系使用的是unsubscribeByEventType(subscriber, eventType);方法:

private void unsubscribeByEventType(Object subscriber, Class eventType) {
        List 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) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

从subscriptionsByEventType中获取所有订阅事件对应的订阅者(Subscription),遍历订阅者list,找出所有订阅类的Subscription,并从中移除。

注意代码中list的选择删除,每删除一个元素,都有i--;size--;不然就会报索引越界的异常。


发送订阅事件 post(Object event)


    private final ThreadLocal currentPostingThreadState = new ThreadLocal() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

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

    public void post(Object event) {
        // 1
        PostingThreadState postingState = currentPostingThreadState.get();
        List eventQueue = postingState.eventQueue;
        eventQueue.add(event);

        if (!postingState.isPosting) {
            // 2
            postingState.isMainThread = isMainThread();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {
                    // 3
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }
 
 

订阅事件发送主要分三步:

  1. 从currentPostingThreadState中获取当前线程的信息:
  • 当前线程的待发送事件对列
  • 发送状态
    currentPostingThreadState是一个threadLocal对象,为每一个线程存储订阅事件的信息。
  1. 判断当前线程是不是主线程,后面可以看到主线程和子线程发送事件的方式不同
  2. 从头开始逐一将当前线程的订阅事件发送出去,使用postSingleEvent(eventQueue.remove(0), postingState);方法。
    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
            // 1
            List> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class clazz = eventTypes.get(h);
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            // 2
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

注释1处是对于订阅事件的超类和接口一并进行发送,注释2处只发送订阅事件,所以主要关注postSingleEventForEventType(event, postingState, eventClass)方法。

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
        CopyOnWriteArrayList subscriptions;
        synchronized (this) {
            // 1
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    // 2
                    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;
    }

注释1处获取当前订阅事件对应的所有订阅对象;在注释2处逐条进行发送,使用postToSubscription(subscription, event, postingState.isMainThread);方法:

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

可以看出,这里针对订阅方法的注解的不同,发送到不同的线程:

  • POSTING:通过发射直接调用订阅方法,没有线程切换,性能损耗最小
  • MAIN:如果发送事件的线程就是主线程,那就反射调用订阅方法;如果不是,那就将订阅事件加入主线程的发送队列
  • MAIN_ORDER:对于Android,不论在哪个线程发送,都将订阅事件加入主线程的发送队列
  • BACKGROUND:如果发送事件的线程是主线程,那就将事件加入子线程的发送队列;否则直接反射调用订阅方法
  • ASYNC:将事件加入异步发送队列
    反射调用订阅方法比较简单,直接调用invokeSubscriber(subscription, event);方法即可。
    这里主要看看三个发送队列的实现:
  • HandlerPoster mainThreadPoster
  • BackgroundPoster backgroundPoster
  • AsyncPoster asyncPoster
    发送队列都实现了Poster接口的void enqueue(Subscription subscription, Object event);方法。

HandlerPoster mainThreadPoster

mainThreadPoster的创建为:new HandlerPoster(eventBus, looper, 10);
实现的enqueue()方法和handleMessage()方法如下:

    @Override
    public void enqueue(Subscription subscription, Object event) {
        // 1
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            // 2
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                if (!sendMessage(obtainMessage())) {
                    throw new EventBusException("Could not send handler message");
                }
            }
        }
    }

    @Override
    public void handleMessage(Message msg) {
        boolean rescheduled = false;
        try {
            long started = SystemClock.uptimeMillis();
            while (true) {
                // 3
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
                // 4
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = SystemClock.uptimeMillis() - started;
                if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }

注释1处创建出一个PendingPost对象,PendingPost对象中包含了订阅事件和订阅对象,为了节省资源避免频繁GC,使用池化的方式重复利用一组PendingPost对象。
注释2处,将PendingPost对象加入mainThreadPoster的队列中,然后发送一个消息(这里的消息不区分内部的内容,只要发送出去就会在handleMessage处理)。
注释3处,获取到message,就从队列从依次弹出PendingPost对象。
注释4处使用反射的方法执行订阅方法,此时执行的方法已经在主线程中执行。

你可能感兴趣的:(撸EventBus源码)