Created
January 14, 2018 11:28
-
-
Save Sloy/90b6f7110c04615687f62b64aea67644 to your computer and use it in GitHub Desktop.
Kotlin wrappers for observing Firebase Firestore database queries and documents using 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
fun Query.observeLiveData(): FirestoreQueryLiveData { | |
return FirestoreQueryLiveData(this) | |
} | |
fun DocumentReference.observeLiveData(): FirestoreDocumentLiveData { | |
return FirestoreDocumentLiveData(this) | |
} | |
class FirestoreQueryLiveData( | |
private val query: Query | |
) : LiveData<List<DocumentSnapshot>>() { | |
private var listenerRegistration: ListenerRegistration? = null | |
override fun onActive() { | |
super.onActive() | |
logd("onActive $query") | |
listenerRegistration = query.addSnapshotListener { snapshot: QuerySnapshot?, exception: FirebaseFirestoreException? -> | |
if (exception != null) { | |
loge("FirestoreQueryLiveData error", exception) | |
} else { | |
value = snapshot!!.documents | |
} | |
} | |
} | |
override fun onInactive() { | |
super.onInactive() | |
logd("onInactive $query") | |
listenerRegistration?.remove() | |
} | |
} | |
class FirestoreDocumentLiveData( | |
private val documentReference: DocumentReference | |
) : LiveData<DocumentSnapshot>() { | |
private var listenerRegistration: ListenerRegistration? = null | |
override fun onActive() { | |
super.onActive() | |
logd("onActive $documentReference") | |
listenerRegistration = documentReference.addSnapshotListener { snapshot: DocumentSnapshot?, exception: FirebaseFirestoreException? -> | |
if (exception != null) { | |
loge("FirestoreQueryLiveData error", exception) | |
} else { | |
value = snapshot!! | |
} | |
} | |
} | |
override fun onInactive() { | |
super.onInactive() | |
logd("onInactive $documentReference") | |
listenerRegistration?.remove() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment