Last active
October 13, 2019 01:11
-
-
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.
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
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) | |
} |
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
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.