RxBus 開源,基于 RxJava 的 event bus

介紹

RxBus 是一個發布/訂閱模式的事件總線,用法和 EventBus 一樣簡單。RxBus 基于 RxJava 開發,除了擁有和 EventBus
一樣簡單的事件總線機制之外,還擁有 RxJava 的豐富特性。

圖片發自簡書App

如何使用

  1. 定義 EventData:

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

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

     @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. 發送數據:

    // send data in thread

    Data data = new Data();

    Data.setContent("hello world");

    RxBus.getInstance().send(data);

比 EventBus 多的優點

RxBus 提供 chainProcess 方法來包裝一個處理過程, 處理結果會自動發送到觀察者。

圖片發自簡書App
  1. 在 MVP 架構的 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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容