EventBus3.0使用(三)

作者: qiaoStr | 来源:发表于2016-07-26 23:32 被阅读395次

上一篇EventBus3.0使用(二)

优先级和事件取消

EventBus也有优先级之分,和广播类似的,优先级越高,那么就越先获得事件的回调,并且也可以取消资格事件,就不继续往下分发事件了。但是有一点需要注意的,取消事件只允许在ThreadMode在ThreadMode.PostThread的事件处理方法中。

定义优先级 Priorities

@Subscribe(priority = 1)
public void onEvent(MessageEvent event) {
  …
}

优先高的会优先比优先级低的接收到事件,默认优先级为0,并且并不会因为ThreadMode而影响到顺序。

取消事件传递

@Subscribe
public void onEvent(MessageEvent event){
// Process the event
  …
EventBus.getDefault().cancelEventDelivery(event) ;
}

事件通常是由更高优先级的用户取消。并且仅限于在发布线程运行ThreadMode.PostThread事件处理。

订阅者索引

对于上面所描述的EventBus的功能,是通过Java反射来获取订阅方法,这样以来大大降低了EventBus的效率,同时也影响了我们应用程序的效率。其实对于反射的处理解析不仅仅只能够通过Java反射的方式来进行,还能够通过apt(Annotation Processing Tool)来处理。为了提高效率,EventBus提供这中方式来完成EventBus的执行过程。下面就来看一下对于EventBus的另一种使用方式。

  • 添加以下到Gradle build
buildscript {    
   dependencies {        
       classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'    
    }
}
apply plugin: 'com.neenbedankt.android-apt'
dependencies {    
    compile 'org.greenrobot:eventbus:3.0.0'    
    apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
}
apt {    
arguments {        
    eventBusIndex "com.example.myapp.MyEventBusIndex"    
   }
}
  • 在当我们使用EventBus以后,在我们的项目没有错误的情况下重新rebuild之后会在build目录下面生成MyEventBusIndex文件,文件名可以自定义。下面就来看一下如何使用这个MyEventBusIndex。
      我们可以自定义设置自己的EventBus来为其添加MyEventBusIndex对象。代码如下所示:
EventBus eventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();
  • 我们也能够将MyEventBusIndex对象安装在默认的EventBus对象当中。代码如下所示:
EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();
// Now the default instance uses the given index. Use it like this:
EventBus eventBus = EventBus.getDefault();

剩下对于EventBus的用法则是一模一样。当然也建议通过添加订阅者索引这种方式来使用EventBus,这样会比通过反射的方式来解析注解效率更高。

相关文章

  • EventBus3.0使用(三)

    上一篇EventBus3.0使用(二) 优先级和事件取消 EventBus也有优先级之分,和广播类似的,优先级越高...

  • EventBus3.0 一

    EventBus3.0 使用 EventBus基本使用发送事件注册接收(main posting backgrou...

  • EventBus3.0使用(一)

    3Steps简单使用EventBus3.0 在使用EventBus 先在Gradle 添加依赖 定义Event事件...

  • EventBus3.0使用(二)

    上一篇EventBus3.0使用(一) Sticky Events 粘性事件 Sticky Events可以允许事...

  • EventBus3.0使用

    EventBus是使用十分广泛的事件总线框架, 2.0到3.0的变化还是挺大的 今天准备重构代码,关于解耦想到了用...

  • EventBus3.0使用

    由于最近更新了EventBus3.0,里面的onEvent方法改变了,在此坐下记录,方便自己以后查阅及使用。Eve...

  • 自己实现简单的EventBus功能

    1、下面是EventBus3.0的一些用法和源码分析 EventBus使用详解 EventBus源码解析 2、接...

  • EventBus 如何发送延时事件

    在项目中使用了EventBus3.0,遇到个场景需要延时执行某动作,想用EventBus进行类似postDelay...

  • EventBus源码详解,看这一篇就够了

    之前写过一篇关于EventBus的文章,大家的反馈还不错(EventBus3.0使用详解),如果你还没有使用过Ev...

  • EventBus3.0的使用

    相信Android的同志们都知道这个玩意,github16k的存在神器,但是这几天遇到一个问题,在一个activi...

网友评论

    本文标题:EventBus3.0使用(三)

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