介紹
RxBus 是一個發布/訂閱模式的事件總線,用法和 EventBus 一樣簡單。RxBus 基于 RxJava 開發,除了擁有和 EventBus
一樣簡單的事件總線機制之外,還擁有 RxJava 的豐富特性。
圖片發自簡書App
如何使用
-
定義 EventData:
public static class EventData { /* Additional fields if needed */ }
-
注解定義訂閱者的回調方法,回調方法回在 UI 線程中執行:
@RegisterBus public void onMessageEvent(MessageEvent event) {/* Do something */};
-
注冊/解注冊。 觀察者需要被注冊到 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); }
發送數據:
// send data in thread
Data data = new Data();
Data.setContent("hello world");
RxBus.getInstance().send(data);
比 EventBus 多的優點
RxBus 提供 chainProcess 方法來包裝一個處理過程, 處理結果會自動發送到觀察者。
圖片發自簡書App
-
在 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; } });
-
然后在 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'
}