EventBus 源码分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Androidtalent/article/details/82535106

本篇文章是EventBus的源码分析,以了解其实现的精髓`。EventBus是针对Android优化的发布-订阅事件总线,简化了Android组件间的通信。Github地址:EventBus

一、注册 register 源码分析

我们在使用 EventBus 的时候,一般通过EventBus.getDefault().register(this); 进行注册,注册的内部实现是

public void register(Object subscriber) {
        // 首先获得class对象
        Class<?> subscriberClass = subscriber.getClass();
        // 通过 subscriberMethodFinder 来找到订阅者订阅了哪些事件.返回一个 SubscriberMethod 对象的 List, SubscriberMethod
        // 里包含了这个方法的 Method 对象,以及将来响应订阅是在哪个线程的 ThreadMode ,以及订阅的事件类型 eventType ,以及订阅的优
        // 先级 priority ,以及是否接收粘性 sticky 事件的 boolean 值,其实就是解析这个类上的所有 Subscriber 注解方法属性。
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                // 订阅
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

再看到 subscribe(subscriber, subscriberMethod);

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        // 获取方法参数的 class
        Class<?> eventType = subscriberMethod.eventType;
        // 创建一个 Subscription
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        // 获取订阅了此事件类的所有订阅者信息列表
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            // 线程安全的 ArrayList
            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++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }
        // 通过 subscriber 获取  List<Class<?>>
        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.get(eventType);来拿,那 subscriptionsByEventType 又是什么呢?追寻看到

private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;

是一个 HashMap,key 是 获取方法参数的 class,value 存放的是 Subscription 的集合列表,value 中的 CopyOnWriteArrayList 是一个线程安全的 ArrayList,数据类型是 Subscription,Subscription包含两个属性,一个是 subscriber 订阅者(反射执行对象),一个是 subscriberMethod 注解方法的所有属性参数值。

二、发送 post 源码分析

/** Posts the given event to the event bus. */
    public void post(Object event) {
        // currentPostingThreadState 是一个 ThreadLocal,
        // 他的特点是获取当前线程一份独有的变量数据,不受其他线程影响。
        PostingThreadState postingState = currentPostingThreadState.get();
        // postingState 就是获取到的线程独有的变量数据
        List<Object> eventQueue = postingState.eventQueue;
        // 把 post 的事件添加到事件队列
        eventQueue.add(event);
        // 如果没有处在事件发布状态,那么开始发送事件并一直保持发布状态
        if (!postingState.isPosting) {
            // 是否是主线程
            postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
            // isPosting = true
            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;
            }
        }
    }

看到上面有个 postSingleEvent(eventQueue.remove(0), postingState);

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        // 得到事件的Class
        Class<?> eventClass = event.getClass();
        // 是否找到订阅者
        boolean subscriptionFound = false;
        // 如果支持事件继承,默认为支持
        if (eventInheritance) {
            // 查找 eventClass 的所有父类和接口
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                // 依次向 eventClass 的父类或接口的订阅方法发送事件
                // 只要有一个事件发送成功,返回 true ,那么 subscriptionFound 就为 true
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            // 发送事件
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        // 如果没有订阅者
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

看到 postSingleEventForEventType(event, postingState, clazz);

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            // 得到Subscription 列表
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            // 遍历 subscriptions
            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(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 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);
        }
    }

可以看到,这里的会判断 threadMode,处理消息都是最终走 invokeSubscriber(subscription, event);

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

可以看到,它是利用调用反射 Method.invoke(),进行方法的执行。

三、解绑 unregister 源码分析

/** Unregisters the given subscriber from all event classes. */
    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 {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

typesBySubscriber 是个 HashMap,key 是所有的订阅者,value 是所有订阅者里面方法的参数的class,在 中的 subscribe 源码分析通过

typesBySubscriber.put(subscriber, subscribedEvents);

来保存。再看到将订阅者的订阅信息移除 unsubscribeByEventType(subscriber, eventType);

/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        // 获取事件类的所有订阅信息列表,将订阅信息从订阅信息集合中移除,同时将订阅信息中的active属性置为FALSE
        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) {
                    // 将订阅信息激活状态置为FALSE
                    subscription.active = false;
                    // 将订阅信息从集合中移除
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

总结:以上便是 EventBus 的源码分析,EventBus 非常好用,希望我们在会用的同时了解好其原理。感谢辉哥。

参考:https://www.jianshu.com/p/0b35f448acec

猜你喜欢

转载自blog.csdn.net/Androidtalent/article/details/82535106