Home > Mobile >  Why should we do network call in ViewModel (Android)?
Why should we do network call in ViewModel (Android)?

Time:09-10

We use ViewModels for storing and manipulating data that is to be used by Views in Activity/Fragment - as data in ViewModel survives configuration change which helps us to retain UI state. It is one of the reasons we do network call operations in ViewModel, but is there any other reason we do network call operations in ViewModel?

I read somewhere that if we do network calls in ViewModels, the call does not happen again on configuration change? But I'm pretty sure API call is happening again in my Fragment on changing device orientation.

CodePudding user response:

We keep api hit in viewModel because of following reasons as per my practices 1)It reduces the coupling between Android components and non Android components 2)You can reuse the same ViewModel for some other screen as well 3) After fetching data you store that data in you liveData holder which can be used data to your UI on it's configuration change without making api hit

CodePudding user response:

To overcome this problem you can call your function in init method of viewmodel makeApiCall() to prevent second call due to onViewCreated method. And you can store api result into livedata.

Alternatively, You can also use LiveData scope like this:

val makeApiCall: () -> LiveData<List<Data>> = {
    liveData {
        emit(repository.fetchData()) // API call
    }
}

Call makeApiCall lambda function from your onViewCreated, now API call will emit only one time and your live data will get observed in onViewCreated.

  1. This is the one of the main advantage of viewmodel to prevent API call on orientation change.

  2. Another advantage is, Suppose if you close the screen and now API call is no longer needed so, if you are using RxJava you need to cancel/dispose API call to release resource so you can perform it in onCleared method of viewModel irrespective of orientation change.

Or if you are using coroutine you can use LiveData scope and viewModel scope no need to care about canceling coroutine. it's managed by self.

  • Related