As the title says, I want to know the difference between addValueEventListener()
and addListenerForSingleValueEvent()
of Firebase.
Asked
Active
Viewed 3.6k times
29

AL.
- 36,815
- 10
- 142
- 281

Mehdi Glida
- 547
- 2
- 5
- 11
-
2Is this not covered in the documentation? – Eric Hauenstein Jan 10 '17 at 21:54
-
no i think..... – Mehdi Glida Jan 10 '17 at 23:40
-
3Both of the listeners are actually well documented in [the official documentation](https://firebase.google.com/docs/database/android/read-and-write#listen_for_value_events). Read **Listen for value events** and **Read data once** section – Wilik Jan 11 '17 at 10:35
1 Answers
59
addValueEventListener()
keep listening to query or database reference it is attached to.
But addListenerForSingleValueEvent()
executes onDataChange
method immediately and after executing that method once, it stops listening to the reference location it is attached to.

Nabin Bhandari
- 15,949
- 6
- 45
- 59

Mohammed Junaid
- 1,362
- 14
- 18
-
1so if i want to keep listening i have to use addValueEventListener() – Mehdi Glida Jan 10 '17 at 23:34
-
yes. ad you need to remove the listener when its not needed.. e.g if you add the listener in OnCreate() it would be a good practice to remove it in OnDestroy(). – Mohammed Junaid Jan 11 '17 at 08:59
-
1I have tried them in code and I have noticed the following, addListenerForSingleValueEvent() get the value value more than once also gives a datasnapshot directly to your refrence for example console.firebase.google.com/any/any/database/data/this, it's datasnapshot is key=this, value= its children, while addValueEventListene, key=children of this and vlaue= children of key's children, so will you explain to me or review the answer again please ? – Dasser Basyouni Mar 01 '17 at 06:44
-
2@DasserBasyouni I agree with you, I have observed that addListenerForSingleValueEvent() gets invoked more than once. – Sreekanth Karumanaghat Oct 18 '17 at 11:58
-
The below link answers another question while making a little comparison between the two methods. https://stackoverflow.com/questions/38017765/retrieving-child-value-firebase – Red M Nov 06 '17 at 15:20
-
Is this self evident? I mean Im little confused, is this self explanatory like some of the native call back methods like onClick()?. I doubt it. – Sreekanth Karumanaghat Mar 05 '18 at 07:25
-
3@SreekanthKarumanaghat It does look like self explanatory. The number of times you call the singleEventValueListener, it get triggers once every time it is called. While on the other hand addValueEventListener() fetches the value every time the value is changed in your firebase realtime DB node to which it is referencing. – Mohammed Junaid Mar 05 '18 at 09:15