RxBus 開(kāi)源,基于 RxJava 的 event bus

介紹

RxBus 是一個(gè)發(fā)布/訂閱模式的事件總線,用法和 EventBus 一樣簡(jiǎn)單。RxBus 基于 RxJava 開(kāi)發(fā),除了擁有和 EventBus
一樣簡(jiǎn)單的事件總線機(jī)制之外,還擁有 RxJava 的豐富特性。

圖片發(fā)自簡(jiǎn)書(shū)App

如何使用

  1. 定義 EventData:

      public static class EventData { /* Additional fields if needed */ }
    
  2. 注解定義訂閱者的回調(diào)方法,回調(diào)方法回在 UI 線程中執(zhí)行:

      @RegisterBus
      public void onMessageEvent(MessageEvent event) {/* Do something */};
    
  3. 注冊(cè)/解注冊(cè)。 觀察者需要被注冊(cè)到 RxBus,其 @RegisterBus 標(biāo)記的方法才會(huì)被掃描到,在不需要的地方記得解注冊(cè)。

     @Override
     protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       initView();
       // register to RxBus
       RxBus.getInstance().register(this);
     }
    
     @Override
     protected void onDestroy() {
         super.onDestroy();
         // unregister from RxBus
         RxBus.getInstance().unRegister(this);
     }
    
  4. 發(fā)送數(shù)據(jù):

    // send data in thread

    Data data = new Data();

    Data.setContent("hello world");

    RxBus.getInstance().send(data);

比 EventBus 多的優(yōu)點(diǎn)

RxBus 提供 chainProcess 方法來(lái)包裝一個(gè)處理過(guò)程, 處理結(jié)果會(huì)自動(dòng)發(fā)送到觀察者。

圖片發(fā)自簡(jiǎn)書(shū)App
  1. 在 MVP 架構(gòu)的 M 層你可以這樣用

     RxBus.getInstance().chainProcess(new Func1() {
         @Override
         public Object call(Object o) {
             // do something in IO thread, the return data can be subscribe and receive.
             // getUser() is a IO/net process
             User user = getUser();
             user.setId(uid);
             user.setName("大利貓");
             return user;
         }
     });
    
  2. 然后在 P 層接收:

        /**
        * @RegisterBus mark this method to receive data in UI thread
        * @param user
        */
    
        @RegisterBus
    
        public void onUser(User user) {
    
          userView.showUser(user);
    
        }
    

Gradle independence

Step 1. Add the JitPack repository to your build file, Add it in your root build.gradle at the end of repositories:

    allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

Step 2. Add the dependency

    dependencies {
        compile 'com.github.liuguangli:RxBus:1.1'
    }

源碼地址

https://github.com/liuguangli/RxBus

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容