EventBus源码分析

  以下代码分析基于eventbus:3.1.1
  EventBus用于安卓模块间通信。下面来看一下它是如何实现的。
  从入口开始,首先注册EventBus,假设在Activity的onCreate()方法中注册(下文中的Activity均为注册EventBus的组件)。

EventBus.getDefault().register(this);

  EventBus的getDefault()方法返回一个单例的EventBus对象:

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

  接着是注册:

public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        //注释1:利用反射获取当前类添加了@subscribe注解的方法。
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            //遍历所有的方法,逐一绑定。
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //注释2:将方法和订阅者以键值对的形式储存起来。
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

  其中findSubscribeMethods方法会取出Activity中的所有带@Subscribe注解的方法,并包装成SubscriberMethod对象,然后放在集合中返回。
  获取完所有要注册的方法后会进行真正的注册。其实就是把Activity和带注解的方法按类别储存起来,以便在发送消息的时候直接拿来用。

// Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //看过findSubscriberMethods方法就知道,注解方法的参数有且只能有一个,eventType就是这个参数的类型。
        Class<?> eventType = subscriberMethod.eventType;
        //将Activity和方法包装起来。
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //尝试获取按参数类别分类的集合
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            //如果没有这样的集合就新建一个,键是参数的类型,值是一个集合,里面的所有Activity的订阅方法都是对应的参数类型。
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        int size = subscriptions.size();
        //在考虑优先级的情况下把Activity和方法的包装对象放到集合中。
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        //按Activity来存储参数类型
        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);
            }
        }
    }

  注册EventBus大概就是做了以上几件事。总结一下就是:

1.先拿出订阅者的所有带有@Subscribe注解的方法。
2.按方法参数的类型把订阅者和方法作为一个整体存储起来。
3.按订阅者保存其内所有方法的参数类型。

  分析到这里EventBus的消息机制也能猜出来一半了。当我们post一个变量时,EventBus会根据这个变量的类型来把这个变量发送到所有已注册并且参数类型相同的方法中。调用方式应该是反射。
  下面对于post方法的分析可以验证我的猜想:

public void post(Object event) {
        //currentPostingThreadState是一个ThreadLocal。
        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;
            }
        }
    }

  首先来看一下postingState。可以发现其是从ThreadLocal获取的。
  了解ThreadLocal的同学一定能想到Handler。Handler机制中的Looper也是存放在ThreadLocal中的。这是因为ThreadLocal能够保证每个线程的数据独立。觉得疑惑的同学请看我的这篇博客
  由于currentPostingThreadState重写了ThreadLocal的initialValue()方法,因此这里的postingState不会获取到null值。消息队列(eventQueue)也会随着postingState的初始化而初始化。
  经过以上的分析,可以得出结论:

1.调用EventBus的post方法会把消息放到消息队列中。
2.消息队列是线程独立的,每个线程有自己的消息队列(类似Handler中的MessageQueue)。
3.每次调用post方法会把当前线程消息队列中的消息全部发送出去。

  接下来就要看看具体是怎么发消息的了:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {//默认false
            List<Class<?>> 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 {
            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));
            }
        }
    }

  实际上调用的是postSingleEventForEventType()方法:

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            //从按参数类型分类的集合中拿出对应的Activity集合。
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            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;//回去抛异常。
    }

  在这里按参数类型取出目标Activity集合,然后真正的去利用反射involk对应的方法。

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

  在这里会对注解的参数进行具体判断,如果要求子线程调用,则会从线程池取出线程来调用方法,如果在主线程调用,会判断当前线程,如果是主线程则直接调用,否则利用handler回到主线程再调用。

猜你喜欢

转载自blog.csdn.net/m0_37988298/article/details/79940988
今日推荐