EventBus3.0源码分析

212 阅读6分钟

什么是EventBus

根据官方介绍,eventbus是一个通过分布/观察者模式实现的消息总线,支持不同线程的调用,能极大的降低代码的耦合度。

EventBus的设计

先上图,官方介绍流程图如下

也很简单,就是通过Publisher post事件到eventbus,之后发送给subscriber进行处理。很明显事件的分发处理在eventbus中,那我们就先从eventbus开始看起。

EventBus实现

实例获取方式如下,典型的单例模式:

 /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

再来看一下构造方法:

/**
     * Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
     * central bus, consider {@link #getDefault()}.
     */
    public EventBus() {
        this(DEFAULT_BUILDER);
    }

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

初始化一些成员变量,同时获取builder中的默认参数进行初始化。

上图是eventbus的成员变量,通过变量名不难知道,主要是做了3部分的缓存:

  1. 当前发送的事件类型的class(eventTypes),包含事件的父类以及实现的接口。这意味着当发送事件时,注册了事件父类的方法也会收到回调。
  2. 事件类型作为Key,Subscription(包含Subscriber和一个SubscriberMethod)的List集合作为Value的Map集合。
  3. 订阅者(Subscriber)作为Key,事件类型作为Value的Map集合。

Subscriber的注册流程

/**
     * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
     * are no longer interested in receiving events.
     * <p/>
     * Subscribers have event handling methods that must be annotated by {@link Subscribe}.
     * The {@link Subscribe} annotation also allows configuration like {@link
     * ThreadMode} and priority.
     */
    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.findSubscriberMethods()获取到subscriberMethods,并进行了subscribe操作。

订阅方法的查找以及缓存操作


List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
		//先取缓存中的数据
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

		//这是3.0新增的属性,是否强制使用反射的方式获取订阅方法
        if (ignoreGeneratedIndex) {
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
        //这边如果没有配置自定义的MyEventBusIndex还是使用反射的方式获取
            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;
        }
    }

说一下里面的主要方法findUsingReflection(),这里通过反射的方式获取到有的注册过的方法,并查找父类同样注册过的方法。查找的方式也是比较简单:

  1. 获取到所有的public修饰的,
  2. 不包含Modifier.ABSTRACT、Modifier.STATIC、BRIDGE、SYNTHETIC中的修饰
  3. 只有一个注解就是Subscribe的方法,最后缓存在METHOD_CACHE中。我们来看具体的代码实现
 private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
 		//这里就是初始化了一个FindState,通过while循环获取订阅类以及其父类的订阅方法,并做了缓存
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

主要的查找实现逻辑其实是在findUsingReflectionInSingleClass()中,也就是开始上面我们说的查找的规则,里面调用到的一个方法需要说一下,就是FindState.checkAddWithMethodSignature()这个方法

private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
            methodKeyBuilder.setLength(0);
            methodKeyBuilder.append(method.getName());
            methodKeyBuilder.append('>').append(eventType.getName());

            String methodKey = methodKeyBuilder.toString();
            Class<?> methodClass = method.getDeclaringClass();
            Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
            
            //这里判断了父类注册的方法是否被子类注册了
            if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
                // Only add if not already found in a sub class
                return true;
            } else {
                // Revert the put, old class is further down the class hierarchy
                subscriberClassByMethodKey.put(methodKey, methodClassOld);
                return false;
            }
        }

这个方法主要是判断了父类注册的方法是否被子类重写,如果被重写根据这个结果会抛出异常,限制了我们的子类去重写父类注册的方法。

注册事件监听以及注销

上面说的方法的查询其实是注册的一部分,下面我们看方法查询完毕之后是怎么被注册上的。

public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

很简单在subscribe()就是把查询出来的每个方法遍历操作,逐个生成Subscription,进行了缓存。

  1. 对重复注册的操作进行了抛出异常的处理,防止重复注册
  2. 在事件注册的同时还根据event注册时的优先级做了排序操作,之后缓存在内存中
  3. 对于sticky事件,这里在subscriber被注册时直接取出并交由subscriber进行了处理。

相对应的,在unregister()中,传入subscriber,将保存在subscriptionsByEventType已经typesBySubscriber中的缓存清除。

事件的发送

    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,并将需要发送的event插入队列中。PostingThreadState中保存了一个事件的队列、是否正在发送消息、是否在主线程、当前发送的事件、当前需要同时的订阅对象以及是否取消等的参数。

循环开启发送当个事件的操作,交由postSingleEvent()处理。

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
            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) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

这里eventInheritance的一个操作就是是否获取事件的父类并做处理,如果需要则获取所有的父类,并依次处理。

接下来就是事件的发送了

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            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;
    }

这里就是一个循环操作,将之前以eventType为key保存的所有Subscription获取出来,并处理event的过程。

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

上面就是最后的事件的分发处理的逻辑了,根据注册时指定的线程类型,发送到对应的线程中进行处理。

到此整个Eventbus事件注册,以及发送处理的逻辑都完毕了。

总结

总结几个关键点:

  1. 事件默认回调的线程是事件发送所在的线程,当然我们可以指定回调的线程;
  2. 事件回调的方法注意线程同步问题;
  3. 事件注册时,如果eventInheritance为true,则发送事件时,注册了监听事件的父类的方法也会收到回调,默eventInheritance认值为true;
  4. 子类在注册时,会遍历所有的父类,并注册父类的监听;