I searched a lot on forums and stackoverflow but I was not able to find a satisfying answer. While observable fields work great with data binding in my view models, why should I use a Live Data object instead?
I know that Live Data is lifecycle aware and it only updates the UI in activity/fragment's active state, but is it really much better to use Live Data instead of Observable fields? Because I am working on a finance app project and it really doesn't do much ui work with observables but it updates the ui only whenever it receives a server response which requires a user interaction.
Also when the activity is destroyed, do fragment's view model and its data still stay in memory? If not -and I suppose not - what is the advantage of live data over observables about memory leak?
why should I use a Live Data object instead?
You do not have to use LiveData
. It is an option, nothing more.
I know that Live Data is lifecycle aware and it only updates the UI in activity/fragment's active state, but is it really much better to use Live Data instead of Observable fields?
You are going to have to deal with the lifecycle somehow. If you prefer to manually dispose of your Rx subscriptions, or if you want to use a library for that, you are welcome to do so. Some will prefer to wrap their Rx types in LiveData
using LiveDataReactiveStreams
or similar mechanisms, so they will clean up automatically based on the activity/fragment lifecycle.
Also, not everybody uses RxJava. RxJava has a substantial learning curve, and some developers would prefer to skip it. For them, just using LiveData
directly can be useful.
Also when the activity is destroyed, do fragment's view model and its data still stay in memory?
That depends on your implementation.
For example, suppose that by "fragment's view model", you mean that you are using the Jetpack ViewModel
system. In that case:
If the activity is being destroyed as part of a configuration change, all ViewModel
objects scoped to that activity and its fragments will be retained across the configuration change
If the activity is being destroyed because it is truly finished, all ViewModel
objects scoped to that activity and its fragments will be garbage collected when the activity itself is garbage collected
what is the advantage of live data over observables about memory leak?
Again, at some point, you need to dispose()
your RxJava Disposable
objects. Whether you do that yourself, use a library, or rely upon LiveData
wrappers is up to you.