RxJava 程式庫

RxJava 是一種回應式程式設計庫,能夠以可觀察序列編寫非同步和事件型程式。

Maps Rx 程式庫可讓您在 Maps SDK for Android 和 Places SDK for Android 中接收非同步事件的可觀察序列,以便充分運用豐富的 RxJava 功能。

安裝

如要在 Google 地圖專案中安裝 Maps Rx 程式庫,請按照下列步驟操作:

  1. 將以下依附元件加進模組層級 build.gradle 檔案:

    dependencies {
        // RxJava bindings for the Maps SDK
        implementation 'com.google.maps.android:maps-rx:1.0.0'
    
        // RxJava bindings for the Places SDK
        implementation 'com.google.maps.android:places-rx:1.0.0'
    
        // It is recommended to also include the latest Maps SDK, Places SDK and RxJava so you
        // have the latest features and bug fixes.
        implementation "com.google.android.gms:play-services-maps:18.2.0"
        implementation 'com.google.android.libraries.places:places:3.4.0'
        implementation 'io.reactivex.rxjava3:rxjava:3.1.8'
    
  2. 在 Android Studio 中重新建立專案,以同步處理這些變更。

使用範例

取得標記點擊事件的可觀察項目,做為 GoogleMap 物件的延伸函式:

googleMap.markerClickEvents()
  .subscribe { marker ->
    Log.d("MapsRx", "Marker ${marker.title} was clicked")
  }

下一個範例說明如何使用 RxJava 運算子 merge,將各種相機事件合併為單一可觀測串流:

Observable.merge(
  googleMap.cameraIdleEvents(),
  googleMap.cameraMoveEvents(),
  googleMap.cameraMoveCanceledEvents(),
  googleMap.cameraMoveStartedEvents()
).subscribe {
  // Notified when any camera event occurs
}

後續步驟