Created
November 25, 2020 10:46
-
-
Save Zhuinden/8fd1349dc21aea0847dbe4e33daa8a35 to your computer and use it in GitHub Desktop.
Firestore queries as LiveData
This file contains 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
inline fun <reified T> Query.asLiveData(noinline onError: ((Throwable) -> Unit) = {}): FirestoreQueryLiveData<T> { | |
return FirestoreQueryLiveData(this, T::class.java, onError) | |
} | |
inline fun <reified T> DocumentReference.asLiveData(noinline onError: ((Throwable) -> Unit) = {}): FirestoreDocumentLiveData<T> { | |
return FirestoreDocumentLiveData(this, T::class.java, onError) | |
} | |
class FirestoreQueryLiveData<T>( | |
private val query: Query, | |
private val clazz: Class<T>, | |
private val onError: ((Throwable) -> Unit) = {} | |
) : LiveData<List<T>>() { | |
private var listenerRegistration: ListenerRegistration? = null | |
override fun onActive() { | |
listenerRegistration?.remove() | |
listenerRegistration = query.addSnapshotListener { snapshot, error -> | |
if (error != null) { | |
onError(error) | |
return@addSnapshotListener | |
} | |
this.value = snapshot?.toObjects(clazz) // value caches the previous query -> list loads faster | |
} | |
} | |
override fun onInactive() { | |
listenerRegistration?.remove() | |
} | |
} | |
class FirestoreDocumentLiveData<T>( | |
private val docRef: DocumentReference, | |
private val clazz: Class<T>, | |
private val onError: ((Throwable) -> Unit) = {} | |
) : LiveData<T>() { | |
private var listenerRegistration: ListenerRegistration? = null | |
override fun onActive() { | |
listenerRegistration?.remove() | |
listenerRegistration = docRef.addSnapshotListener { snapshot, error -> | |
if (error != null) { | |
onError(error) | |
return@addSnapshotListener | |
} | |
this.value = snapshot?.toObject(clazz) | |
} | |
} | |
override fun onInactive() { | |
listenerRegistration?.remove() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment