I read these blog posts written by Doug Stevenson Part 1, Part 2, Part 3. On part 2 he says that
The Realtime Database SDK makes it really easy to convert a DataSnapshot into a JavaBean style object
And mentions that we can use this line of code to get the DataSnapshot deserialized into a HotStock object (a JavaBean class)
HotStock stock = dataSnapshot.getValue(HotStock.class)
I´m confused because he first uses Transformation.map and then he says that if a LiveData transformation is expensive we can create a MediatorLiveData object from the ViewModel to get the DataSnapshot converted into a HotStock object.
My question is: Why can´t we just call the
HotStock stock = dataSnapshot.getValue(HotStock.class)
from the onDataChange() method on the ValueEventListener which resides in the class extending the LiveData super class and then simply use the setValue() method to pass the HotStock object directly to the ViewModel and then to the Activity or Fragment observing for changes to the LiveData?
You can do that, but getValue()
passing a class object is actually kind of slow (especially the first time, for a particular class) because the SDK has to use reflection to figure out how to map all the fields into the object it creates. Java reflection known to be fairly slow. But it's up to you what you want to use.