1

I am using Firebase Realtime Database. I want to listen only for specific data that is added when user opened the app and so on. This is the code:

databaseReference = firebaseDatabase!!.getReference("chat")
    databaseReference!!.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            Log.i("DDM", "Data Changed")
        }

        override fun onCancelled(error: DatabaseError) {
            Log.i("DDM", "Error While Messaging")
        }
    })

Here is the database: Database picture

I specifically want to add a listener for data insertion and not fetch previous data when the listener is registered.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Junaid Khan
  • 315
  • 5
  • 16
  • 1
    Is the "chat" node, a direct child of the root node? You want to get the deviceId and message, right? What do you mean by "not fetch previous data when the listener is registered"? – Alex Mamo May 12 '21 at 14:07
  • Chat is direct child of root node – Junaid Khan May 12 '21 at 15:08
  • I mean when I register for listerners such as value event listener or child event listener, they trigger some data on startup with all the data stored. I want to listen for data change only when new data is inserted when app is started. – Junaid Khan May 12 '21 at 15:10

1 Answers1

1

when I register for listeners such as value event listener or child event listener, they trigger some data on startup with all the data stored

Yes, that's the expected behavior. When you are attaching a ValueEventListener, you'll always get in the callback a DataSnapshot object that contains all the objects that exist at the location to which the listener is added to. So there is no way you can skip the initial data and get only the new data that is inserted/updated/deleted. If you need o more granular callback response you can use a ChildEventListener, but you'll encounter the exact same behavior.

Unfortunately, Firebase listeners don't work that way. What you can do instead, is to add under each "Chat" object a timestamp property, here is how you can do it, and then query your database on the client, according to this new property, for all nodes that have changed since a previous time. In this way, you'll be able to get only what's new.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193