Skip to content

Instantly share code, notes, and snippets.

@yaraki
Created May 20, 2019 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaraki/8032ac9ae9fbe0ce05e7109974bd82ee to your computer and use it in GitHub Desktop.
Save yaraki/8032ac9ae9fbe0ce05e7109974bd82ee to your computer and use it in GitHub Desktop.
Firebase Query as LiveData
/**
* Copyright 2019 Google LLC.
* SPDX-License-Identifier: Apache-2.0
*/
package com.example.firestore
import android.util.Log
import androidx.lifecycle.LiveData
import com.google.firebase.firestore.*
private const val TAG = "FirestoreLiveData"
fun <T> Query.toLiveData(convert: QuerySnapshot.() -> T): LiveData<T> {
return object : LiveData<T>(), EventListener<QuerySnapshot> {
private var listenerRegistration: ListenerRegistration? = null
override fun onEvent(snapshot: QuerySnapshot?, e: FirebaseFirestoreException?) {
if (e != null) {
Log.w(TAG, "Listen failed", e)
return
}
if (snapshot != null && !snapshot.isEmpty) {
value = convert(snapshot)
}
}
override fun onActive() {
listenerRegistration = addSnapshotListener(this)
}
override fun onInactive() {
listenerRegistration?.remove()
}
}
}
/**
* Copyright 2019 Google LLC.
* SPDX-License-Identifier: Apache-2.0
*/
package com.example.firestore
import androidx.lifecycle.LiveData
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
class SampleRepository(
private val firestore: FirebaseFirestore
) {
fun liveMessages(): LiveData<List<String>> {
return firestore.collection("messages")
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(25)
.toLiveData {
documents.map { d ->
d["text"] as String
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment