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

圖片發(fā)自簡(jiǎn)書(shū)App
如何使用
-
定義 EventData:
public static class EventData { /* Additional fields if needed */ } -
注解定義訂閱者的回調(diào)方法,回調(diào)方法回在 UI 線程中執(zhí)行:
@RegisterBus public void onMessageEvent(MessageEvent event) {/* Do something */}; -
注冊(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); } 發(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
-
在 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; } }); -
然后在 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'
}