RxBus 用法学习总结

来源:互联网 发布:淘宝宝贝综合排名 编辑:程序博客网 时间:2024/06/06 09:54
        文档上都是代码,就是没注释,刚开始看的时候,有些地方不知道咋回事,记录一下。 添加到自己的项目中,很简单
 compile ('com.hwangjr.rxbus:rxbus:1.0.5') {    exclude group: 'com.jakewharton.timber', module: 'timber' }

       使用方式有两种,直接使用com.hwangjr.rxbus.RxBus或者使用单例模式得到一个对象

       public static final class RxBus{

       private static Bus mBus;

       public static synchronized Bus getInstance(){

      if(mBus == null){

      mBus = new Bus();

      }

      return mBus;

      }   

      }

      文档上推荐使用第二种方式。

      我遇到的第一个问题是RxBus是不是可以像BroadCast一样,可以跨页面,在哪都能收到广播,然后测试了下,只有当在当前界面和接收消息的页面都     RxBus.get().register(this),才能收到消息。

      我遇到的第二个问题是RxBus.get().post()和@Produce的用法和区别。

      第一眼看文档确实没怎么看懂,

      

@Subscribe    public void eat(String food) {        // purpose    }    @Subscribe(        thread = EventThread.IO,        tags = {            @Tag(BusAction.EAT_MORE)        }    )    public void eatMore(List<String> foods) {        // purpose    }    @Produce    public String produceFood() {        return "This is bread!";    }    @Produce(        thread = EventThread.IO,        tags = {            @Tag(BusAction.EAT_MORE)        }    )    public List<String> produceMoreFood() {        return Arrays.asList("This is breads!");    }

         普通的不带类型的传值,两种方式1 直接使用RxBus.get().post("hahaha"),2使用@Produce

         @Produce

          public String test(){

          return "hehehehe";

          }

         这时在

         @Subcribe

         public void test(String str){

         Log.d("test",str);

         }中就能收到消息了,上面两种方式的效果是一样的。

        带类型的传值消息,也有两种方式,1 直接使用RxBus.get().post("type","hahahaha"),2使用@Produce

       @Produce(

        thread = EventThread.IO,

        tags = {

        @Tag("type") 

        }

        )

       然后在

      @Subscribe(

       thread = EventThread.IO//线程类型要和produce时的线程类型保持一致。如果使用第一种方式,在点击事件的时候,这里要使用EventThread.MAINTHREAD

       tags = {

       @Tag("type")

       }

       )     

       public void test(String str){

       Log.d("test",str)

       }这里就能收到消息了。使用大概就是这样了,接下来会分析一下源码。

        

1 0
原创粉丝点击