Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Coroutine with Live Data or only Coroutines?

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

like image 484
Sourabh Saldi Avatar asked Jan 27 '23 02:01

Sourabh Saldi


1 Answers

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...

  1. You'll end up with a suspending call like 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.
  2. If you're handling cancellation for your coroutines (which you probably should be), a configuration change will mean that any work you've already done in the 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.
  3. If you're not cancelling your coroutines when the View is destroyed, your data fetching function may attempt to update the UI in a View that doesn't exist any more if when completes.

In comparison, if you start coroutines in your ViewModel and then place the result in a LiveData:

  1. Your fetches can continue across configuration changes due to the ViewModel's longer lifespan.
  2. You can cancel coroutines when your screen is closed for good (in onCleared) instead of at configuration changes.
  3. 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).
  4. When your View is recreated, the new instance can start observing the 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.
like image 182
zsmb13 Avatar answered Jan 31 '23 20:01

zsmb13