美文网首页
浅析EventBus3.x (Android)

浅析EventBus3.x (Android)

作者: karlsu | 来源:发表于2018-02-23 18:55 被阅读50次

什么是EventBus?

基于观察者模式的事件发布/订阅框架,支持同一个进程的组件(比如Activity, Fragment, Service, 线程)之间的通信.相比于接口,EventBus通过极少的代码实现模块间的通信,无须层层传递。具有易上手,性能高,接入成本低,耦合度低等优点。

EventBus事件处理流程图

EventBus.png

新手上路——使用EventBus

1. 添加依赖

在 build.gradle 中添加依赖:

compile 'org.greenrobot:eventbus:3.1.1'

2. 添加索引

在EventBus 3.0版本中引入了 EventBusAnnotationProcessor(注解分析生成索引)技术,大大提高了EventBus的运行效率,可根据实际情况自行决定要不要添加

在项目gradle的dependencies中引入apt编译插件:

classpath'com.neenbedankt.gradle.plugins:android-apt:1.8'

在App的build.gradle中应用apt插件,并设置apt生成的索引的包名和类名:

apply plugin: 'com.neenbedankt.android-apt'
 
dependencies {
    compile 'org.greenrobot:eventbus:3.1.1'
    apt 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}
 
apt {
    arguments {
        eventBusIndex "com.example.myapp.MyEventBusIndex"
    }
}

对于用了Android Studio 3.0的同学按照如上设置之后会报错
Error:android-apt plugin is incompatible with the Android Gradle plugin. Please use 'annotationProcessor' configuration instead.

看错报错信息之后,想必应该知道怎么回事了,Android studio3.0,Gradle已经和这个不兼容了,正确的配置姿势是这样的。

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [ eventBusIndex : 'com.example.myapp.MyEventBusIndex' ]
            }
        }
    }
}
 
dependencies {
    compile 'org.greenrobot:eventbus:3.1.1'
    annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}

3. 初始化

EventBus默认有一个单例,可以通过getDefault()获取,也可以通过EventBus.builder()构造自定义的EventBus,比如要应用我们生成好的索引时:

EventBus mEventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();

如果想把自定义的设置应用到EventBus默认的单例中,则可以用installDefaultEventBus()方法:

EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();

4. 自定义事件

public class BusEvent {
    private Object mObject;
    private int mType;

    public BusEvent() {
    }
  }

5.监听事件

首先把作为订阅事件的模块通过EventBus注册监听:

mEventBus.register(this);

在3.0之前,注册监听需要区分是否监听黏性(sticky)事件,监听EventBus事件的模块需要实现以onEvent开头的方法。如今改为在方法上添加注解的形式:

@Subscribe(threadMode = ThreadMode.MAIN,priority = 0, sticky = true)
    public void onMessageEvent(BusEvent event) {
        switch (event.getType()) {
            case BusEvent:
                doSomething();
                break;
        }
    }

注解有三个参数,threadMode为回调所在的线程,priority为优先级,sticky为是否接收黏性事件。调度单位从类细化到了方法,对方法的命名也没有了要求,方便混淆代码。但注册了监听的模块必须有一个标注了Subscribe注解方法,不然在register时会抛出异常:
Subscriber class XXX and its super classes have no public methods with the @Subscribe annotation

6. 发送事件

调用post或者postSticky即可:

EventBus.getDefault().post(new BusEvent(BusEvent.EV_TASK_TRANSFER_SUCCESS));

7. 取消注册事件

 EventBus.getDefault().unregister(this);

以上即是EventBus3的使用方法,是不是很简单?下面我们来研究下内部原理

~~~~吃饭之后,待续~~~~~

官方文档说明
PS:该文章仅供个人学习之用,学识浅薄,不当之处,还请指出!

相关文章

网友评论

      本文标题:浅析EventBus3.x (Android)

      本文链接:https://www.haomeiwen.com/subject/flvztftx.html