0

I set the listener if isNeedToListen = true, otherwise I remove it, but it still works and I have set listeners that contradict each other when I enter the same chat room from different accounts

override fun listenMessage(
    receiver_id: String,
    user_id: String,
    messages: MutableLiveData<ArrayList<Message>>,
    onSuccess: (ArrayList<Message>) -> Unit,
    isNeedToListen:Boolean
) {
    var listenUserMessage: ListenerRegistration? =  null
    var listenReceiverMessage: ListenerRegistration? =  null
    if(isNeedToListen){
        listenUserMessage = database
            .collection(KEY_COLLECTION_USERS)
            .document(user_id)
            .collection(KEY_COLLECTION_CHAT)
            .addSnapshotListener { value, error -> ...
            }

        listenReceiverMessage = database
            .collection(KEY_COLLECTION_USERS)
            .document(receiver_id)
            .collection(KEY_COLLECTION_CHAT)
            .addSnapshotListener { value, error ->...
            }
    }else{
        if(listenUserMessage !=null){
            listenUserMessage.remove()
        }
        if(listenReceiverMessage !=null){
            listenReceiverMessage.remove()
        }
    }

}

UPD isNeedToListen coming from

firebaseRepostory.listenMessage(receiver_id, user_id, messages, onSuccess,false)

this code is executed onStop()

firebaseRepostory.listenMessage(receiver_id, user_id, messages, onSuccess,true)

this code is executed onStart()

Danil
  • 41
  • 5
  • Where is `isNeedToListen` coming from? Can show us more context? – Alex Mamo Sep 09 '22 at 07:52
  • @AlexMamo I added the information – Danil Sep 09 '22 at 08:09
  • 1
    And why do you say it is still active? Besides that, have you read [this](https://stackoverflow.com/questions/48699032/how-to-set-addsnapshotlistener-and-remove-in-populateviewholder-in-recyclerview/)? – Alex Mamo Sep 09 '22 at 08:15
  • @AlexMamo because it's still active, and yes I read that – Danil Sep 09 '22 at 08:41
  • 1
    @AlexMamo I am very stupid, I had to make my listeners global, I am very inconsiderate, thank you very much – Danil Sep 09 '22 at 08:49
  • From the above comment, I believe that your issue is solved. Can you post your answer as a solution? So that, it will be useful for others who are facing same issue – Roopa M Sep 13 '22 at 05:00

1 Answers1

1

Declaring a global listener would solve this problem. For more information refer this StackOverflow Thread shared by @AlexMamo.

Roopa M
  • 2,171
  • 4
  • 12