EventBus源码分析一

1.Event概述

1.1EventBus是什么?

EventBus是一个使用发布-订阅模式(观察者模式)进行松耦合的Android开源库。EventBus能够通过仅仅几行代码使解耦的类进行基本的通信 - 简化代码,消除依赖和加速app开发。

1.2使用EventBus的好处?/为什么要是用它?

  • 简化组件之间通信
  • 分离事件的发送者和接收者
  • 简化 Activities, Fragments, Threads, Services之间通信,更少的代码,更好的质量
  • 避免复杂和容易出错的依赖关系和生命周期问题
  • 快速,高效的
  • 小(<50K的jar)
  • 具有交付线程、用户优先级等高级功能

greenrobot官方对EventBus的解释

1.3EventBus中三个重要的角色

  • 事件(Event):也可理解为消息,事件可以是任意类型对象。事件类型(EventType)指事件所属的类。

事件分为一般事件和 Sticky (粘性)事件,相对于一般事件,Sticky 事件不同之处在于,当事件发布后,再有订阅者开始订阅该类型事件,依然能收到该类型事件最近一个 Sticky 事件。

  • 订阅者(Subscriber):订阅某种事件类型的对象。

当有发布者发布这类事件后,EventBus 会执行订阅者的 onEvent 函数,这个函数叫事件响应函数。订阅者通过 register 接口订阅某个事件类型,unregister 接口退订。订阅者存在优先级,优先级高的订阅者可以取消事件或者继续向优先级低的订阅者分发,默认所有订阅者优先级都为 0。

  • 发布者(Publisher):发布某事件的对象,可以通过post接口在任意线程任意位置发送事件。

1.4EventBus架构图

下面这个是greenrobot官方提供的图就很直观的说明了Event的架构:


理解:

  • EventBus 负责存储Subscriber和Event,Subscriber和Publisher都只和 EventBus 关联。
  • EventBus执行流程:Subscriber首先调用 EventBus 的 register 接口订阅某种类型的事件,当Publisher通过 post 接口发布该类型的事件时,EventBus 执行Subscriber的事件响应函数。

2.EventBus源码分析

2.1创建EventBus

我们就从EventBus.getDefault()入手,看看EventBus是如何初始化的:

    static volatile EventBus defaultInstance;
 /** 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;
    }

可以看出来,EventBus是单例模式存在的,并且是进程范围内共享的。除了通过静态函数 getDefault 获取EventBus单例对象,也可以通过 EventBusBuilder (Builder模式创建复杂对象)或 构造函数创建一个 EventBus对象。

设计模式之单例模式
设计模式之Builder模式

需要注意的是:
每个新建的 EventBus 发布和订阅事件都是相互隔离的,即一个 EventBus 对象中的发布者发布事件,另一个 EventBus 对象中的订阅者不会收到该订阅。

EventBus构造方法重要代码:

    private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

    public EventBus() {
        this(DEFAULT_BUILDER);
    }

    //key:事件的class对象,value:订阅这个事件的订阅者集合
    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    //key:订阅者对象,value:这个订阅者所订阅的事件类型集合
    private final Map<Object, List<Class<?>>> typesBySubscriber;
    //key:粘性事件的class对象, value:粘性事件对象
    private final Map<Class<?>, Object> stickyEvents;
    //事件主线程处理
    private final HandlerPoster mainThreadPoster;
    //事件 Background 处理
    private final BackgroundPoster backgroundPoster;
    //事件异步线程处理
    private final AsyncPoster asyncPoster;
    //订阅者事件响应函数信息存储和查找类
    private final SubscriberMethodFinder subscriberMethodFinder;
    //是否支持事件继承
    private final boolean eventInheritance;

    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);
        
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);

        eventInheritance = builder.eventInheritance;

        ...

    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • EventBus源码分析(一) EventBus官方介绍为一个为Android系统优化的事件订阅总线,它不仅可以很...
    蕉下孤客阅读 4,047评论 4 42
  • 前言# 之前在聊观察者模式的时候说过之后要来个EventBus的源码分析,今天就开始补上。 首先我们做一点准备工作...
    珠穆朗玛小王子阅读 727评论 0 0
  • EventBus用法及源码解析目录介绍1.EventBus简介1.1 EventBus的三要素1.2 EventB...
    杨充211阅读 1,917评论 0 4
  • 先吐槽一下博客园的MarkDown编辑器,推出的时候还很高兴博客园支持MarkDown了,试用了下发现支持不完善就...
    Ten_Minutes阅读 579评论 0 2
  • 我每周会写一篇源代码分析的文章,以后也可能会有其他主题.如果你喜欢我写的文章的话,欢迎关注我的新浪微博@达达达达s...
    SkyKai阅读 24,999评论 23 184