which is better between these two
1) Using coroutines in Viewmodel to fetch data from network and updating View using live data?
2) Using coroutine from View to call suspend function in viewmodel that fetches data from network?
Another question
Should we be using livedata for use cases where we need to update UI only once from backend, like data won't be changing while user is on that screen
I'm voting for (1), using LiveData
for that final step of moving the data from the ViewModel
to the View.
Here's why: if you start a coroutine in the UI which fetches the data through your ViewModel
...
getData()
in the View. Whether that's a Fragment
or an Activity
, that coroutine will deliver the result to only that specific instance. If it gets recreated due to a configuration change, you'll need to fetch again in the new instance.ViewModel
and around the network will be lost (e.g. any progress on a long running network call), since your coroutine is cancelled when your View is destroyed.In comparison, if you start coroutines in your ViewModel
and then place the result in a LiveData
:
onCleared
) instead of at configuration changes.LiveData
observers will only be called when the View exists and is in an active (foreground) state, so you don't have to worry about getting results when your View isn't ready for it (or doesn't exist anymore).LiveData
and receive the value that's already loaded. Or, if your data is still loading, it will even eventually receive the result of the network call that was started for a previous View instance.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With