Android EventBus3.x 使用詳解(一)

來源:互聯網
上載者:User

標籤: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 使用詳解(一)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.