I'm making a chat app and I'm using Firestore for real-time conversations. I have a simple snapshot listener and it's working fine, but I need to add filters according to different message types (e. g. images or audio). To reach this I'm using multiple Firestore queries to filter the content, the problem is that as I have multiple listeners, my RecyclerView gets updated with all of them.
I've tried adding the current listener into a variable, then detaching and adding the new one with the filters, but once I remove the first listener and add them again, they're not triggered anymore.
How can I toggle between different listeners, remove or add the one I need and only listen to it?
This is my ViewModel, getChatMessages()
is the default query and getImageMessages
is called when the image filter is applied:
//Current listener
private var listenerRegistration: ListenerRegistration? = null
//Get all messages
fun getChatMessages(id: Int) {
//Remove current listener
listenerRegistration?.remove()
val chatId = "chatroom_$id"
val query = db.collection(chatId).orderBy("timestamp", Query.Direction.DESCENDING)
listenerRegistration = query.addSnapshotListener { value, error ->
//Handle errors and update LiveData with messages
}
}
//Get only image messages
fun getImageMessages(id: Int) {
//Remove current listener
listenerRegistration?.remove()
val chatId = "chatroom_$id"
val query = db.collection(chatId).orderBy("timestamp", Query.Direction.DESCENDING)
.whereEqualTo("typeMessage", "image")
listenerRegistration = query.addSnapshotListener { value, error ->
//Handle errors and update LiveData with messages
}
}