Search code examples
androidapiandroid-fragmentsconfigurationandroid-viewmodel

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


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.


Solution

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