Home > OS >  How to toggle between different Snapshot Listeners with Firestore?
How to toggle between different Snapshot Listeners with Firestore?

Time:11-04

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
    }
}


CodePudding user response:

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).

The following query works fine:

val query = db.collection(chatId).orderBy("timestamp", Query.Direction.DESCENDING)

Because it's a simple query that doesn't require something special to be done. However, the following query:

query = db.collection(chatId).orderBy("timestamp", Query.Direction.DESCENDING)
    .whereEqualTo("typeMessage", "image")

Requires an index, since you're ordering the results on a different field than you perform the whereEqualTo() call. To solve this, please my answer in the following post:

  • Related