EventBus 源码分析(二)----运行原理

接上一篇文章 https://mp.csdn.net/editor/html/105921525

上一篇写了一些关于EventBus 的简单使用,
这一篇我们主要写一下EventBus 的运行原理

注册对象register方法

    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 是一个在EventBus 第一次使用时候就创建好的对象

subscriberMethodFinder.findSubscriberMethods(subscriberClass);

将注册的class 中的方法解析出来 findSubscriberMethods 是关键

查找注册的方法 :findSubscriberMethods

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

这里看到,METHOD_CACHE 是一个存储类Map<Class<?>, List> 包含了注册类和内部接收方法的键值对,用于提高注册时的效率(毕竟后续的反射速度毕竟慢)
继续查看代码findUsingReflection 和 findUsingInfo
我们找到关键类findUsingReflectionInSingleClass

解析接收方法的配置 :findUsingReflectionInSingleClass

用于在对象中找出注册接收反射的方法

    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];//eventType
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();//threadMode
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));//priority sticky
                        }
                    }
                } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                    String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                    throw new EventBusException("@Subscribe method " + methodName +
                            "must have exactly 1 parameter but has " + parameterTypes.length);
                }
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException(methodName +
                        " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
            }
        }
    }

代码中我们可以看到,通过反射找出了class 中所有的方法,同时遍历检查 Subscribe 注解的方法是否合法
最终将所有注解参数打包成SubscriberMethod
其中有几点需要记得的属性代码中加入了注释标注

属性描述
eventType实际就是接收的事件对象 ,就是上一篇文章的 SampleEvent
threadMode在方法注册时的Subscribe 类型
priority接收的权重
stickyboolean 值,表示这个消息是否是粘性消息

回到register 方法

通过上面的方式,我们找出了注册对象的所有监听方法
现在继续看subscribe 方法
(删除了一些注释和错误判断)

	// subscriber 注册的对象 subscriberMethod 其中一个接收方法的描述信息
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //------------part 1----------------
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> 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;
            }
        }
//------------part 2----------------
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
//------------part 3----------------
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                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
subscriptionsByEventType 以事件对象和所有接收事件的方法列表组成的键值对
第二部分:构建数据subscribedEvents
subscribedEvents 用来保存注册对象以及他所接收的所有事件列表,这里我们可以看到,EventBus 对priority 权重进行了处理,实际就是根据这个值进行数据排序。
第三部分:处理粘性事件
因为粘性事件会在注册的时候马上发送,所以EventBus 在注册的时候检索了粘性事件列表,然后调用方法checkPostStickyEventToSubscription 去发送
具体粘性事件的运作,后面说了Post 以后返回再了解

发送消息 :Post

    /** Posts the given event to the event bus. */
    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;
            }
        }
    }

这里的currentPostingThreadState 是一个ThreadLocal对象
这里的逻辑是在发送线程中保存下发送的事件。
然后检查当前EventBus是否处于发送状态,如果没有则开始从队列取出消息并且发送

发送前的准备: 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));
            }
        }
    }

这段代码里 lookupAllEventTypes 会找到所有有注册过的所有对象,然后循环调用postSingleEventForEventType 方法

postSingleEventForEventType (这里就不贴代码了) 内部我们看到
EventBus 通过register 步骤构建的subscriptionsByEventType 中找出所有接收的方法
依次调用postToSubscription 去进行发送

根据不同的threadMode 发送消息:postToSubscription

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

postToSubscription 内部根据注册接收方法的threadMode 不同使用不同的策略进行发送,

POSTING

其中 invokeSubscriber 最终调用的代码为

subscription.subscriberMethod.method.invoke(subscription.subscriber, event);

这里用了反射去调用最终的方法

MAIN

mainThreadPoster 实际是一个Handler

mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);

看到实例化方式可以看出,他是一个运行在主线程的Handler ,所以为什么EventBus 能向主线程发送Event 了

BACKGROUND

backgroundPoster 实际是一个Runnable

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

可以看到在enqueue 的时候,像队列里加入一个消息,并且启动线程,其中getExecutorService 最终获得的是一个ExecutorService , 他是这么创建的

Executors.newCachedThreadPool()

可以看出他就是最简单的线程池去处理background 的事件

ASYNC

asyncPoster 也是一个Runnable 对象
相比backgroundPoster 少了很多线程锁之类的判断,因为在Async 模式下,默认开启一个独立的线程去发送消息

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        queue.enqueue(pendingPost);
        eventBus.getExecutorService().execute(this);
    }

发送粘性事件:postSticky

    public void postSticky(Object event) {
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event);
    }

这里看到,在发送粘性事件以前,只是很简单将粘性事件保存了下来,并且进行了一次发送
那么粘性事件是怎么被发送的呢
回到register 过程中的subscribe 的代码
当注册的时候,会检查注册的粘性事件是否有匹配的,如果有的话,调用postToSubscription 进行发送

解除注册:unRegister

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

这里就没有什么太复杂的了,主要是将注册时保存下来的键值对信息进行删除

EventBus 整个框架有什么值得学习的

1、整体框架和功能解决了我们开发数据中的痛点
2、其中应用了单例模式、建造者模式等设计模式。整体代码干净好理解。
3、整体数据存储的思路很值得学习,register 过程可以看到,不断包装map 和list 去储存注册对象和方法
4、方法锁和对象锁的使用,作为跨线程的数据总线工具,保证了整体的数据逻辑
5、注解和反射,EventBus 使用方便的一个重要支持,使用注解和反射的方式获取回调的方法和调用的对象。

不断学习和进步
欢迎有什么不明白或者错误的请评论区指出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值