Android EventBus源码深入解析

news2024/9/28 15:22:39

前言

EventBus:是一个针对Android进行了优化的发布/订阅事件总线。
github对应地址:EventBus
大家肯定都已经比较熟悉了,这里重点进行源码分析;

EventBus源码解析

我们重点从以下三个方法入手,弄清楚registerunregister以及post方法,自然就能够明白EventBus的工作原理;

EventBus.getDefault().register

    public void register(Object subscriber) {
		...
        Class<?> subscriberClass = subscriber.getClass();
        1.获取subscriberMethods集合;
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
            	2.进行事件订阅;
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

我们可以看出register方法主要做了如下两件事:

  • 获取subscriberMethods集合;
  • 进行事件订阅;
  1. 我们先分析第一步, subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    	//1.首先从缓存中取,METHOD_CACHE是一个ConcurrentHashMap,以subscriberClass为key,List<SubscriberMethod>为value
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
		//ignoreGeneratedIndex属性表示是否忽略注解器生成的MyEventBusIndex,默认为false,为apt自动生成代码,这里跟踪反射处理代码,重点跟下findUsingReflection(subscriberClass)
        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;
        }
    }

我们继续看下findUsingReflection(subscriberClass)

    private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        FindState findState = prepareFindState(); //这里使用了享元设计模式,从缓存池中取出FindState对象
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

继续分析findUsingReflectionInSingleClass(findState);

    private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
        	1.findState.clazz即为register入参clazz,可理解为activityClazz
        	首先反射获取activityClazz中的所有方法
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
        	...
        }
        2.遍历所有方法,过滤是public方法
        for (Method method : methods) {
            int modifiers = method.getModifiers();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {			3.获取方法对应参数clazz
                Class<?>[] parameterTypes = method.getParameterTypes();
                4.方法参数个数必须为1if (parameterTypes.length == 1) {
                 5.解析Subscribe注解
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        Class<?> eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            6.将方法名、参数clazz、注解对应的threadmode、priority、sticky包装成SubscriberMethod对象并保存到findState.subscriberMethods中;
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    }
    		....
        }
    }

分析完了subscriberMethods集合的创建过程后,我们在看下subscribe(subscriber, subscriberMethod)都做了什么?

   private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
   		1.获取subscriberMethod.eventType,对应的就是subscribe注解方法入参的clazz
        Class<?> eventType = subscriberMethod.eventType;
        2.构造Subscription对象
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        3.subscriptionsByEventType为HashMap类型,根据eventType获取subscriptions;
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        4.以eventType为key,CopyOnWriteArrayList<Subscription>为value,保存Subscription数据到subscriptionsByEventType中
        if (subscriptions == null) {
            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;
            }
        }
		5.构建typesBySubscriber对象,typesBySubscriber是为subscriber为key【可以理解为activity对象】,subscribedEvents为value【存储注解方法参数clazz的集合】
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
		...
    }

小结:当调用register方法时,会通过反射(ignoreGeneratedIndex为true的情况下)解析注册对象所有的subscribe注解方法(方法必须为public并且参数个数为1)保存到subscriberMethods集合中,接着遍历subscriberMethods集合,构建subscriptionsByEventTypetypesBySubscriber的hashMap集合;

下面针对一些重要的对象中保存的数据进行简单的绘图:

  • SubscriberMethod对象结构
    subscriberMethod保存数据
  • SubscriptionsByEventType对象结构
    SubscriptionsByEventType保存数据
  • typesBySubscriber对象结构
    typesBySubscriber保存数据

EventBus.getDefault().post

下面我们再看下发布事件

    public void post(Object event) {
    	//currentPostingThreadState为ThreadLocal类,保证一个线程只有一份postingState
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        //1.将event添加到事件队列中
        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 {
            	//2.判断事件是不是正在post状态,不是的话不断遍历eventQueue,从前往后取event
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

postSingleEvent最终会调用postSingleEventForEventType方法

  private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
        	//1.根据post的数据类型clazz,从subscriptionsByEventType集合中获取subscriptions集合;
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
        2.遍历subscriptions集合,调用postToSubscription方法
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted;
                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方法:

 private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
 		//根据threadMode属性分别执行不同逻辑;
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
            	//如果是同一线程执行,直接执行invokeSubscriber
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
            	//如果是主线程执行,判断当前线程是否处于主线程中,不是的话通过Handler切换到主线程并调用invokeSubscriber
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case MAIN_ORDERED:
            	//如果是主线程优先,主线程poster不为空,则调用主线程执行,否则直接执行invokeSubscriber
                if (mainThreadPoster != null) {
                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    invokeSubscriber(subscription, event);
                }
                break;
            case BACKGROUND:
            	//后台线程执行,如果是主线程调用线程池执行,否则直接执行invokeSubscriber
                if (isMainThread) {
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC:
            //异步执行,直接通过线程池执行invokeSubscriber
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }

	//实际上就是通过反射执行subscribe注解的方法
   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);
        }
    }

小结:调用post方法,会根据post入参对象的clazz查找subscriptionsByEventType集合拿到subscriptions【里面保存的有subscriber和subscribermethod】,然后遍历subscriptions集合,根据ThreadMode执行不同的线程策略,最终均是通过反射执行subscribe注解的方法;

EventBus.getDefault().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 {
        }
    }

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

unregister逻辑比较简单,只是清除subscriptionsByEventTypetypesBySubscriber集合中保存的数据,防止内存泄漏;

优先级和粘性事件实现

我们直接看下subscribe方法:

 private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    	...
    	//1.Priority优先级处理部分
    	//保存Subscription到subscriptions集合中时,会根据priority进行排序,priority高的排在前面,
    	//从上面post的时候我们看到最终会顺序遍历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;
            }
        }

        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
			
		//2.粘性处理部分
		// stickyEvents为ConcurrentHashMap集合,key对应post方法参数的clazz,value为post方法参数对象,在调用postSticky的时候,保存到stickyEvents集合中;
		//这里判断是sticky方法,则在register的时候就调用postToSubscription方法进行执行了,因此实现了粘性事件,对于后注册先发送的事件也可以接受到!!
        if (subscriberMethod.sticky) {
        		....
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
  
        }
    }


    private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        if (stickyEvent != null) {
            postToSubscription(newSubscription, stickyEvent, isMainThread());
        }
    }

EventBus中的设计模式

  • 享元设计模式:FindState数据获取;
    private FindState prepareFindState() {
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                FindState state = FIND_STATE_POOL[i];
                if (state != null) {
                    FIND_STATE_POOL[i] = null;
                    return state;
                }
            }
        }
        return new FindState();
    }
  • 建造者设计模式:EventBus支持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;
    }
  • 单例设计模式:EventBus对象;
    public static EventBus getDefault() {
        EventBus instance = defaultInstance;
        if (instance == null) {
            synchronized (EventBus.class) {
                instance = EventBus.defaultInstance;
                if (instance == null) {
                    instance = EventBus.defaultInstance = new EventBus();
                }
            }
        }
        return instance;
    }	

总结

看到EventBus的源码,整体代码架构还是比较清晰,阅读起来也比较轻松,其中一些设计思路也比较常见,如设计模式的运用、缓存机制等等,自己也可以跟着源码简单手写一个属于自己的EventBus

结语

如果以上文章对您有一点点帮助,希望您不要吝啬的点个赞加个关注,您每一次小小的举动都是我坚持写作的不懈动力!ღ( ´・ᴗ・` )

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/150477.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

关于sql注入这一篇就够了(适合入门)

本文章根据b站迪总课程总结出来,若有不足请见谅 目录 存在sql注入条件 判断数据库类型 注入mysql思路 判断网站是否存在注入点 判断列名数量&#xff08;字段数&#xff09; 文件读写操作 网站路径获取方法 注入类型 按注入点数据类型来分类 根据提交方式分类 猜测查询方式 sql…

(Java高级教程)第三章Java网络编程-第四节:TCP流套接字(ServerSocket)编程

文章目录一&#xff1a;Java流套接字通信模型二&#xff1a;相关API详解&#xff08;1&#xff09;ServerSocket&#xff08;2&#xff09;Socket三&#xff1a;TCP通信示例一&#xff1a;客户端发送什么服务端就返回什么&#xff08;1&#xff09;代码&#xff08;2&#xff0…

量子计算(二十一):Deutsch-Josza算法

文章目录 Deutsch-Josza算法 Deutsch-Josza算法 量子算法是量子计算落地实用的最大驱动力&#xff0c;好的量子算法设计将更快速推动量子计算的发展。 Deutsch-Jozsa量子算法&#xff0c;简称D-J算法&#xff0c;DavidDeutsch和RichardJozsa早在1992年提出了该算法&#xff0…

分布式事务方案分析:两阶段和TCC方案(图+文)

1 缘起 补充事务相关知识过程中&#xff0c; 发现&#xff0c;默认的知识都是基于单体服务的事务&#xff0c;比如ACID&#xff0c; 然而&#xff0c;在一些复杂的业务系统中&#xff0c;采用微服务架构构建各自的业务&#xff0c; 就有了分布式事务的概念&#xff0c;比如&am…

一站式云原生体验|龙蜥云原生ACNS + Rainbond

关于 ACNS 龙蜥云原生套件 OpenAnolis Cloud Native Suite&#xff08;ACNS&#xff09;是由龙蜥社区云原生 SIG 推出的基于 Kubernetes 发行版本为基础而集成的套件能力&#xff0c;可以提供一键式部署&#xff0c;开箱即用&#xff0c;以及丰富的云原生基础能力&#xff0c;…

JProfiler的使用

一、安装 从https://www.ej-technologies.com/download/jprofiler/files获取&#xff0c;如果需要对服务器远程分析&#xff0c;注意服务器版本的jprofiler和windows版本一致。 二、监控一个本地进程 2.1 不使用idea 安装之后&#xff0c;打开jprofiler&#xff0c;点击红框…

电脑蓝屏并提示BAD_POOL_CALLER怎么办?

电脑蓝屏可以说是Windows的常见问题&#xff0c;各种各样的终止代码对应着不同的问题。如果你的蓝屏代码显示BAD_POOL_CALLER&#xff0c;这篇文章就是为你提供的。 可能导致BAD_POOL_CALLER蓝屏错误的原因&#xff1a; 1、硬件或软件不兼容 2、过时或错误的设备驱动程序 3…

DataWorks创建JavaUDF函数全流程

文章目录插件下载创建MaxCompute Studio项目创建MaxCompute Java Module编写Java UDF函数注意说明&#xff1a;这篇文章只是个人记录下&#xff0c;具体步骤都可以在官网找到。推荐看官网文档哈 插件下载 创建MaxCompute Studio项目 启动IntelliJ IDEA&#xff0c;在顶部菜单栏…

1806. 还原排列的最少操作步数

解法一&#xff1a; 根据题目的题目描述进行模拟&#xff0c;遇到偶数iii将arr[i]prem[i/2]arr[i] prem[i/2]arr[i]prem[i/2],遇到奇数iii,将arr[i]prem[(n−1i)/2]arr[i]prem[(n-1i)/2]arr[i]prem[(n−1i)/2] 时间复杂度: O(n2)O(n^2)O(n2), 最多会循环n次空间复杂度&#…

Nginx反向代理使用方法小总结

文章目录一、前言二、反向代理定义重申三、短网址方式代理四、多级域名方式代理五、通配符代理方式总结一、前言 本文只介绍代理转发到一个主机的方式&#xff0c;至于在代理时进行负载均衡大家需要自己尝试&#xff0c;也比较简单&#xff0c;在本专栏前面文章提到过&#xf…

(二)Redis概述与安装

目录 一、概述 1、特性 2、应用场景 二、安装 三、启动 1、前台启动&#xff08;不推荐&#xff09; 2、后台启动&#xff08;推荐&#xff09; 四、redis关闭 五、redis相关知识介绍 一、概述 1、特性 Redis是一个开源的key-value存储系统。和Memcached类似&#x…

TOOM舆情分析监控管理系统集成,舆情监控系统监测那些人群?

当前&#xff0c;互联网已成为思想文化信息的集散地和社会舆论的扩大器&#xff0c;舆情监控新闻、论坛博客、聚合新闻等等&#xff0c;做好舆情监控&#xff0c;至于监测那些人群&#xff0c;舆情分析监控是非常必要的&#xff0c;接下来我们简单了解TOOM舆情分析监控管理系统…

接口协议之抓包分析 TCP 协议

TCP 协议是在传输层中&#xff0c;一种面向连接的、可靠的、基于字节流的传输层通信协议。环境准备对接口测试工具进行分类&#xff0c;可以如下几类&#xff1a;网络嗅探工具&#xff1a;tcpdump&#xff0c;wireshark代理工具&#xff1a;fiddler&#xff0c;charles&#xf…

《移动通信》多章节部分重要习题(简答、单选、判断)

调制技术在移动通信中的作用&#xff1f; 调制有两个目的: 1 )经过调制可以使基带信号变换为带通信号。选择需要使用的载波频率 ( 简称载频 ) ,可以把信号的频谱从开始的频段转移到到所需要的频段上,从而使传输信号适应信道的要求,或是可以把许多个输入信号合起来应用于多路传…

开发模型 和 测试模型 详解

开发模型 开发模型 &#xff1a; ① 瀑布模型 ② 螺旋模型 ③ 增量模型 和 迭代模型 ④ 敏捷模型 (优点 缺点 适用场景)测试模型 &#xff1a; ① V模型 ② W模型瀑布模型优点/特点&#xff1a;线性结构&#xff0c;每个阶段 只执行一次是其他模型的一个基础框架缺点&#xff1…

sentinel-Roadmap(三)

Pages 60 Sentinel 官方网站 OpenSergo 微服务治理 文档 Read Me新手指南Sentinel 介绍FAQRoadmap如何使用工作原理流量控制集群流控&#xff08;分布式流控&#xff09;网关流控熔断降级热点参数限流系统自适应限流黑白名单控制实时监控数据动态规则控制台生产环境使用 Sent…

Spring依赖注入时,创建代理bean和普通bean详解

问题来源 以前一直有个疑惑&#xff0c;为什么我创建的controller中注入的service类有时候是代理类&#xff0c;有时候是普通javabean&#xff0c;当时能力不够&#xff0c;现在已经有了点经验就大胆跟了跟源码&#xff0c;看看到底咋回事。 首先看看问题现象&#xff1a; a1…

linux nfs umount报错:device is busy

执行nfs卸载命令umount /mnt&#xff0c;报错target is busy. 或device is busy可以按以下步骤检查&#xff1a;退出要卸载挂载的目录&#xff0c;再执行卸载挂载cd ../umount /mnt找出占用目录的端口&#xff0c;kill端口fuser -m /mnt/kill -9 端口umount /mnt停止nfs服务&am…

PCA 主成分分析-清晰详细又易懂

PCA&#xff08;Principal Component Analysis&#xff09;通过线性变换将原始数据变换为一组各维度线性无关的表示&#xff0c;可用于提取数据的主要特征分量&#xff0c;常用于高维数据的降维。 当然我并不打算把文章写成纯数学文章&#xff0c;而是希望用直观和易懂的方式叙…

Java char[]数组转成String类型(char to String)详细介绍

前言 string toCharArray() 方法将给定的字符串转换为字符序列 Java中字符串转换为字符数组的方法在之前的博客已经介绍了&#xff01; 今天介绍char[]数组转成String 方法有4种&#xff1a; 使用 String 类的 valueOf() 方法使用字符串连接使用 Character 类的 toString() 方…