1

I have an event listener attached to firebase. But the event listener is called twice on a datachange. I feel that I am not removing the listener properly. Can someone please guide here is my code:

I have the listener inside onStart() as follows

        ref5 = appRef.orderByChild("*****").equalTo(*****)
        listenerApp = ref5.addValueEventListener(object: ValueEventListener {
            override fun onCancelled(p0: DatabaseError) {
                Toast.makeText(this,"Error", Toast.LENGTH_LONG).show()
            }

            override fun onDataChange(p0: DataSnapshot) {

  // Do Something
    }
  })

The listener is detached as follows inside onStop()

if((this::listenerApp.isInitialized)&&(this::ref5.isInitialized)) ref5.removeEventListener(listenerApp)

Where am I getting wrong?

One more thing is that the listener is not always evoked twice. It happens occasionally

oTwo
  • 185
  • 2
  • 13
  • Check out my answer here. https://stackoverflow.com/a/73677221/7042992 The 2nd trigger in my case was due to ServerValue.TIMESTAMP in the data. – Vikram Baliga Sep 11 '22 at 06:15

1 Answers1

0

Why not listen for the data once, using addListenerForSingleValueEvent:

listenerApp = ref5.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
Toast.makeText(this,"Error", Toast.LENGTH_LONG).show()
}
.....
.....
.....
Hasan Bou Taam
  • 4,017
  • 2
  • 12
  • 22
  • My problem is of listener getting evoked twice on one single data change. I cannot use single value event listener because the data changes multiple number of time – oTwo Apr 30 '20 at 20:28