【Android】EventBus 3.x使用APT提升性能

本文介绍如何使用APT生成SubscriberIndex以提高EventBus3.0的性能,包括集成步骤及原理分析。

前言

EvenBus 2.x时代的消息订阅只能使用固定的方法名,比如:

onEvent
onEventMainThread
onEventBackgroundThread
onEventAsync

从EventBus 3.0开始支持使用注解来定义消息订阅者(subscriber),方法名是随意的,比如:

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {
   
   
    // Do something
}

不过,EventBus3.0还有一个鲜为人知的功能,而且是一个可选的功能,默认是不带的,需要手动添加支持。

那就是使用APT在编译期间搜集所有的SubscribMethod。默认是在运行期间通过反射去搜集SubscriberMethod,这样性能就差点。

EventBus添加APT支持

在EventBus的github主页上有一个不起眼的地方,有提到建议使用APT(只是建议不是必须使用):
在这里插入图片描述
点击这个链接会跳转到单独介绍如何使用subscriber index(APT生成的代码)的指南页面:
https://greenrobot.org/eventbus/documentation/subscriber-index/

下面通过实践介绍如何使用subscriber index来提升EventBus的性能。

关于EventBus集成subscriber index很简单,先通过kapt额外添加eventbus-annotation-processor依赖:

dependencies {
   
   
 	implementation "org.greenrobot:eventbus:3.2.0"
 	kapt "org.greenrobot:eventbus-annotation-processor:3.2.0"
 }

然后给APT添加参数,注明生成subscriber index类的路径:

   defaultConfig {
   
   
        kapt {
   
   
           arguments {
   
   
               arg('eventBusIndex', 'com.devnn.bean.AppEventBusIndex')
           }
       }
   }

这个类是自动生成的,不需要手动去创建,命名可以随意。

build项目之后就会在build目录生成Java类:com.devnn.bean.AppEventBusIndex.java

然后需要在app启动时将这个类注册进EventBus中:

class MyApp :Application(){
   
   
    override fun onCreate() {
   
   
        super.onCreate()
        EventBus.builder().addIndex(AppEventBusIndex()).build()
    }
}

其它像以前一样正常使用EventBus即可。

关于APT有不了解的可以看笔者另一篇文章:
Google AutoService的使用与源码解析

下面分析这个类的作用。

EventBus APT流程分析

EventBus是通过建造者模式构建的,在EventBusBuilder类通过addIndex方法接收SubscriberInfoIndex对象:

    /** Adds an index generated by EventBus' annotation preprocessor. */
    public EventBusBuilder addIndex(SubscriberInfoIndex index) {
   
   
        if (subscriberInfoIndexes == null) {
   
   
            subscriberInfoIndexes = new ArrayList<>();
        }
        subscriberInfoIndexes.add(index);
        return this;
    }

而SubscriberInfoIndex是一个接口:

package org.greenrobot.eventbus.meta;

/**
 * Interface for generated indexes.
 */
public interface SubscriberInfoIndex {
   
   
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值