闲在家里?看看EventBus解析,跟我一起一起手写EventBus

当你接收的的事件后,如果处于非UI线程,你要更新UI怎么办?如果处于UI线程, 你要进行耗时操作,怎么办?等等其他情况,通过ThreadMode统统帮你解决。

用法展示:

@Subscribe(threadMode = ThreadMode.MainThread)
public void onNewsEvent(NewsEvent event){
String message = event.getMessage();
mTv_message.setText(message);
}

使用起来很简单,通过 @Subscribe(threadMode = ThreadMode.MainThread) 即可指定。 下面具体介绍下ThreadMode

关于ThreadMode,一共有四种模式PostThreadPostThreadBackgroundThread以及Async

PostThread 事件的处理在和事件的发送在相同的进程,所以事件处理时间不应 太长,不然影响事件的发送线程。

MainThread: 事件的处理会在UI线程中执行。事件处理时间不能太长,这个不用说 的,长了会ANR的。

BackgroundThread 如果事件是在UI线程中发布出来的,那么事件处理就会在子 线程中运行,如果事件本来就是子线程中发布出来的,那么事件处理直接在该子线 程中执行。所有待处理事件会被加到一个队列中,由对应线程依次处理这些事件, 如果某个事件处理时间太长,会阻塞后面的事件的派发或处理。

Async 事件处理会在单独的线程中执行,主要用于在后台线程中执行耗时操作, 每个事件会开启一个线程。

2.priority事件优先级

事件的优先级类似广播的优先级,优先级越高优先获得消息。 用法展示:

@Subscribe(priority = 100)
public void onToastEvent(ToastEvent event){
Toast.makeText(MainActivity.this,event.getContent(),Toas t.LENGTH_SHORT).show();
}

当多个订阅者(Subscriber)对同一种事件类型进行订阅时,即对应的事件处理方 法中接收的事件类型一致,则优先级高(priority 设置的值越大),则会先接收事 件进行处理;优先级低(priority 设置的值越小),则会后接收事件进行处理。

除此之外,EventBus也可以终止对事件继续传递的功能。 用法展示:

@Subscribe(priority = 100)
public void onToastEvent(ToastEvent event){
Toast.makeText(MainActivity.this,event.getContent(),Toas t.LENGTH_SHORT).show();
EventBus.getDefault().cancelEventDelivery(event);
}

这样其他优先级比100低,并且订阅了该事件的订阅者就会接收不到该事件。

3.EventBus黏性事件

EventBus除了普通事件也支持粘性事件。可以理解成:订阅在发布事件之后,但同 样可以收到事件。订阅/解除订阅和普通事件一样,但是处理订阅的方法有所不同, 需要注解中添加sticky = true。 用法展示:

@Subscribe(priority = 100,sticky = true)
public void onToastEvent(ToastEvent event){
Toast.makeText(MainActivity.this,event.getContent(),Toas t.LENGTH_SHORT).show();
EventBus.getDefault().cancelEventDelivery(event);
}

这样,假设一个ToastEvent 的事件已经发布,此时还没有注册订阅。当设置了 sticky = true,在ToastEvent 的事件发布后,进行注册。依然能够接收到之前发布 的事件。

不过这个时候,发布事件的方式就改变了。

EventBus.getDefault().postSticky(new ToastEvent(“Toast,发个提示, 避免去人多的地方!”));

我们如果不再需要该粘性事件我们可以移除

EventBus.getDefault().removeStickyEvent(ToastEvent.class);

或者调用移除所有粘性事件

EventBus.getDefault().removeAllStickyEvents();

4.EventBus配置

EventBus在2.3版本中添加了EventBuilder去配置EventBus的各方各面。
比如: 如何去构建一个在发布事件时没有订阅者时保持沉默的EventBus

EventBus eventBus = EventBus.builder()
.logNoSubscriberMessages(false)
.sendNoSubscriberEvent(false)
.build();

通过上述设置,当一个事件没有订阅者时,不会输出log信息,也不会发布一条默认 信息。

配置默认的EventBus实例,使用EventBus.getDefault()是一个简单的方法。获取一 个单例的EventBus实例。EventBusBuilder也允许使用installDefaultEventBus方法 去配置默认的EventBus实例。

注意: 不同的EventBus 的对象的数据是不共享的。通过一个EventBus 对象去发 布事件,只有通过同一个EventBus 对象订阅事件,才能接收该事件。所以以上使 用EventBus.getDefault()获得的都是同一个实例。

四、源码解析
注册订阅

EventBus.getDefault().register(this);

事件处理

@Subscribe(threadMode = ThreadMode.MainThread)
public void onNewsEvent(NewsEvent event){
String message = event.getMessage();
mTv_message.setText(message);
}

发布事件

EventBus.getDefault().post(new NewsEvent(“我是来自SecondActivity 的消息,你好!”));

以上是EventBus的基本使用。我们先从getDefault说起。

getDefault()

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

通过上述代码可以得知,getDefault()中通过双检查锁(DCL)机制实现了 EventBus的单例机制,获得了一个默认配置的EventBus对象。 下面我们继续看 register()方法。

register()

在了解register()之前,我们先要了解一下EventBus中的几个关键的成员变量。方便 对下面内容的理解。

/** Map<订阅事件, 订阅该事件的订阅者集合>
*/
private final Map<Class<?>, CopyOnWriteArrayList> subscriptionsByEventType;

/** Map<订阅者, 订阅事件集合>
*/
private final Map<Object, List<Class<?>>> typesBySubscriber;

/** Map<订阅事件类类型,订阅事件实例对象>.
*/
private final Map<Class<?>, Object> stickyEvents;

下面看具体的register()中执行的代码。

public void register(Object subscriber) {
//订阅者类型
Class<?> subscriberClass = subscriber.getClass();
//判断该类是不是匿名类,如果是匿名累要使用反射
boolean forceReflection = subscriberClass.isAnonymousCla ss();
//获取订阅者全部的响应函数信息(即上面的onNewsEvent()之类的方法)
List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(sub scriberClass, forceReflection);
//循环每一个事件响应函数,执行 subscribe()方法,更新订阅相关信息
for (SubscriberMethod subscriberMethod : subscriberMetho ds) { subscribe(subscriber, subscriberMethod);
}
}

由此可见,register()
第一步 获取订阅者的类类型.
第二步 通过 SubscriberMethodFinder类来解析订阅者类,获取所有的响应函数集合.
第三步 遍历 订阅函数,执行 subscribe()方法,更新订阅相关信息。 关于 subscriberMethodFinder这里就不介绍了。先跟着线索,继续看subscribe()方法。subscribe函数分三步。

第一步:

//获取订阅的事件类型
Class<?> eventType = subscriberMethod.eventType;
//获取订阅该事件的订阅者集合
CopyOnWriteArrayList subscriptions = subsc riptionsByEventType.get(eventType);
//把通过register()订阅的订阅者包装成Subscription 对象 Subscription newSubscription = new Subscription(subscrib er, subscriberMethod);
//订阅者集合为空,创建新的集合,并把newSubscription 加入
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList();

subscriptionsByEventType.put(eventType, subscription s);

} else {
//集合中已经有该订阅者,抛出异常。不能重复订阅
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subs criber.getClass() + " already registered to event " + eventType);
}
}
//把新的订阅者按照优先级加入到订阅者集合中。
synchronized (subscriptions) {
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
if (i == size || subscriberMethod.priority > sub scriptions.get(i).subscriberMethod.priority) { subscriptions.add(i, newSubscription);
break;
}
}
}

第二步:

//根据订阅者,获得该订阅者订阅的事件类型集合
List<Class<?>> subscribedEvents = typesBySubscriber.get( subscriber); //如果事件类型集合为空,创建新的集合,并加入新订阅的事件类型。 if (subscribedEvents == null) { subscribedEvents = new ArrayList

第三步:

//该事件是stick=true。
if (subscriberMethod.sticky) {
//响应订阅事件的父类事件
if (eventInheritance) {
Set<Map.Entry<Class<?>, Object>> entries = stick yEvents.entrySet(); //循环获得每个stickyEvent事件 for (Map.Entry

//是该类的父类
if (eventType.isAssignableFrom(candidateEven tType)) {
//该事件类型最新的事件发送给当前订阅者。
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSu bscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType) ;
checkPostStickyEventToSubscription(newSubscripti on, stickyEvent);
}
}

由此可见,
第一步: 通过subscriptionsByEventType得到该事件类型所有订阅者信 息队列,根据优先级将当前订阅者信息插入到订阅者队列 subscriptionsByEventType中;
第二步:typesBySubscriber中得到当前订阅者订阅的所有事件队列,将此事件保 存到队列typesBySubscriber中,用于后续取消订阅;
第三步: 检查这个事件是否 是 Sticky 事件,如果是则从stickyEvents事件保存队列中取出该事件类型最后一个 事件发送给当前订阅者。

到此,便完成了订阅功能。下面是订阅的具体流程图:

unregister()

public synchronized void unregister(Object subscriber) {
// 获取该订阅者所有的订阅事件类类型集合.
List<Class<?>> subscribedTypes = typesBySubscriber.get(subsc riber); if (subscribedTypes != null) { for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
// 从typesBySubscriber删除该<订阅者对象,订阅事件类类型集合>
typesBySubscriber.remove(subscriber);
} else {
Log.e(“EventBus”, "Subscriber to unregister was not regi stered before: "+ subscriber.getClass());
}
}

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
// 获取订阅事件对应的订阅者信息集合.
List 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()方法比较简单,主要完成了subscriptionsByEventType以及 typesBySubscriber两个集合的同步。

post()

public void post(Object event) {
// 获取当前线程的Posting状态.
PostingThreadState postingState = currentPostingThreadState. get();
// 获取当前线程的事件队列.
List eventQueue = postingState.eventQueue;
//将当前事件添加到其事件队列
eventQueue.add(event);
//判断新加入的事件是否在分发中
if (!postingState.isPosting) {
postingState.isMainThread = Looper.getMainLooper() == Lo oper.myLooper();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException(“Internal error. Abort s tate was not reset”);
}try {
// 循环处理当前线程eventQueue中的每一个event对象.
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingSta te);
}
} finally {
// 处理完知乎重置postingState一些标识信息.
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}

post 函数会首先得到当前线程的 post 信息PostingThreadState,其中包含事件队 列,将当前事件添加到其事件队列中,然后循环调用 postSingleEvent 函数发布队 列中的每个事件。

private void postSingleEvent(Object event, PostingThreadState po stingState) {
//分发事件的类型
Class<?> eventClass = event.getClass(); boolean subscriptionFound = false; //响应订阅事件的父类事件 if (eventInheritance) { //找出当前订阅事件类类型eventClass的所有父类的类类型和其实现的接 口的类类型 List

最后

其实Android开发的知识点就那么多,面试问来问去还是那么点东西。所以面试没有其他的诀窍,只看你对这些知识点准备的充分程度。so,出去面试时先看看自己复习到了哪个阶段就好。

虽然 Android 没有前几年火热了,已经过去了会四大组件就能找到高薪职位的时代了。这只能说明 Android 中级以下的岗位饱和了,现在高级工程师还是比较缺少的,很多高级职位给的薪资真的特别高(钱多也不一定能找到合适的),所以努力让自己成为高级工程师才是最重要的。

这里附上上述的面试题相关的几十套字节跳动,京东,小米,腾讯、头条、阿里、美团等公司21年的面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。

由于篇幅有限,这里以图片的形式给大家展示一小部分。

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
里、美团等公司21年的面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。

由于篇幅有限,这里以图片的形式给大家展示一小部分。

[外链图片转存中…(img-2frcgMRt-1715158961467)]

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值