標籤:HERE 觀察 傳遞 2018年 interface block 使用詳解 通訊 ace
?(^∇^*) 五一假期在家無事,新項目中用的是RxJava2+EventBus感覺還不錯,趁這閑暇總結下EventBus
一、概要簡述
EventBus是一個基於觀察者模式的Android事件發布/訂閱架構,通過解耦發行者和訂閱者簡化Android事件傳遞,這裡的事件可以理解為訊息。事件傳遞既可以用於Android四大組件間通訊,也可以用於非同步線程和主線程間通訊等。
EventBus的出現,是為瞭解決傳統的通過Interface的事件傳遞所出現的回調地獄的問題,相比之下EventBus的有點是代碼簡潔,使用簡單,並將事件發布和 訂閱充分解耦。
EventBus由三部分組成:event事件、subscriber訂閱者、publisher發行者。
EventBus 官網地址:http://greenrobot.org/eventbus/
EventBus GitHub :https://github.com/greenrobot/EventBus
二、基本使用準備工作
添加依賴(兩種方式):
//Via Gradle
compile ‘org.greenrobot:eventbus:3.1.1‘
<!--Via Maven--><dependency> <groupId>org.greenrobot</groupId> <artifactId>eventbus</artifactId> <version>3.1.1</version></dependency>
第一步 定義事件
事件是POJO(普通的舊Java對象),沒有任何特定的要求。
public class MessageEvent { public final String message; public MessageEvent(String message) { this.message = message; }}
第二步 準備訂閱者-Subscriber
// This method will be called when a MessageEvent is posted (in the UI thread for Toast)@Subscribe(threadMode = ThreadMode.MAIN)public void onMessageEvent(MessageEvent event) { Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();} // This method will be called when a SomeOtherEvent is posted@Subscribepublic void handleSomethingElse(SomeOtherEvent event) { doSomethingWith(event);}
訂閱者需要registe和unregist
待續。。2018年4月29日21:00:47
Android EventBus3.x 使用詳解(一)