RxBus開源地址:https://github.com/AndroidKnife/RxBus
參考文章: 1.?Rxbus事件交互?
? ? ? ? ? ? ? ? 2. 關于RxBus的一些使用心得
主要作用
?使用注解的方式實現頁面間/頁面內傳值,可以使用tag對消息進行標記,可以指定線程。
實踐使用
?參照RxBus官方文檔,將RxBus引入工程
?STEP1 :gradle 引入依賴 compile 'com.hwangjr.rxbus:rxbus:1.0.3'
如果工程中使用了 AndroidKnife/Utils/timber,需要將依賴修改成如下:
? ? ? ?compile ('com.hwangjr.rxbus:rxbus:1.0.3') {
? ? ? ? ? ? exclude group: 'com.hwangjr.utils', module: 'timber'
? ? ? ? }
STEP2: 直接使用架包提供的 com.hwangjr.rxbus.RxBus 或 自己寫一個RxBus單例(官方推薦),實現如下:
public static final class RxBus {
? ? ? ? private static Bus sBus;
? ? ? ?public static synchronized get() {
? ? ? ? ? ? ? ?if (sBus == null) {
? ? ? ? ? ? ? ? ? ? ?sBus = new Bus();
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? return sBus;
? ? ? ?}
}
STEP3: 在Activty/Fragment 中使用RxBus,這里的this不是特指Activity,所以在Fragment中不需要用getActivity();(參考2)
? ? 在onCreate()中調用RxBus.get().register(this); ? ?進行注冊操作。
? ? 在onDestory()中進行RxBus.get().unregister(this); ? ? 解綁操作。
STEP4: 在任何需要監聽處理事件的地方,添加如下代碼,實現收到消息的處理事件:
@Subscribe
public void Function(String param) {? // 這里也可以寫成(String tag, Object param)
? ? ? ? ? // TODO
}
STEP5: 在需要發送消息的地方使用 RxBus.get().post(param); or RxBus.get().post(tag, param); // post發消息是主線程
PS:還有一種使用注解發消息的方式,這種方式貌似只適用于在頁面初始化的時候,不能手動控制,但是可以指定線程和tag
例:
監聽實現
//接收一個列表參數,并且限制這個接收線程是IO,標記為BusAction.EAT_MORE ,標記需要和發送者一致,線程不要需要
@Subscribe(
? ? thread = EventThread.MAIN_THREAD,
? ? tags = { ?@Tag(BusAction.EAT_MORE) ?}
)
public void receiveFunction(Object param) {
? ? ? // TODO
}
消息發送
@Produce
public Object sendFunction() {
? ? ? ?// TODO
? ? ? ?return param;
}