Created
May 20, 2019 07:53
-
-
Save yaraki/8032ac9ae9fbe0ce05e7109974bd82ee to your computer and use it in GitHub Desktop.
Firebase Query as LiveData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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() | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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