Skip to content

Instantly share code, notes, and snippets.

@AniketSK
Last active October 13, 2019 01:11
Show Gist options
  • Save AniketSK/4f6dbd4364ed7ef2d3765c40cb26b75b to your computer and use it in GitHub Desktop.
Save AniketSK/4f6dbd4364ed7ef2d3765c40cb26b75b to your computer and use it in GitHub Desktop.
Example of how to watch a Firestore collection for a list of items inside a custom livedata.
package com.aniketkadam.dogether.goals
import androidx.lifecycle.LiveData
import com.aniketkadam.dogether.goals.data.GoalsListLiveData
import com.google.firebase.firestore.FirebaseFirestore
import javax.inject.Inject
class GoalListRepository @Inject constructor(private val firebaseFirestore: FirebaseFirestore) {
fun getOwnGoals(): LiveData<List<Goal>> =
GoalsListLiveData(firebaseFirestore)
}
package com.aniketkadam.dogether.goals.data
import androidx.lifecycle.LiveData
import com.aniketkadam.dogether.goals.Goal
import com.google.firebase.firestore.EventListener
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ListenerRegistration
import com.google.firebase.firestore.QuerySnapshot
class GoalsListLiveData(private val db: FirebaseFirestore) :
LiveData<List<Goal>>() {
private var listenerRegistration: ListenerRegistration? = null
override fun onActive() {
super.onActive()
listenerRegistration = db.collection("user").addSnapshotListener(eventListener)
}
override fun onInactive() {
super.onInactive()
listenerRegistration?.remove()
}
private val eventListener = EventListener<QuerySnapshot> { querySnapshot, e ->
if (e == null && querySnapshot != null) {
value = querySnapshot.toObjects(Goal::class.java)
}
}
}
@AniketSK
Copy link
Author

The only important things here,
onActive is when you register your listeners
onInactive is when you unregister them.

Inside your listeners, you should call setValue which is a method on the LiveData class which you're extending, and pass it the value of the type you're listening to.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment