Home > Mobile >  Android: Is it correct to poll an api in the repository layer?
Android: Is it correct to poll an api in the repository layer?

Time:11-22

I will be injecting this repository class into each of my viewModels that require it. The following is the init block for the repository.

init {
        GlobalScope.launch {
            while(true) {
                when (val response = getData()) {
                    is ApiResponse.Success -> {
                        response.data?.let {
                            data = it
                        }
                    }
                    else -> {}
                }
                delay(5000)
            }
        }
    }

CodePudding user response:

The repository layer should be the holders to make any api call/db operations you should just suspend those functions, I follow MVVM pattern.

While in your viewModel you should fetch the data using coroutines with the help of viewModelscope.launch{ } while inside a viewModel and lifecylceScope.launch{ } if you're making a call from fragment or activity.

Avoid using GlobalScope as it stick with the application class lifecyle, hence not an optimal scope.

I hope I made your doubt clear.

CodePudding user response:

as #Sourabh Bhatt mentioned, you should define api calls inside your repository class as suspend functions and then, inside your viewModel class call that methods by using viewModelScope , that is special coroutine scope to use inside viewModel and that scope is destroyed automatically when viewModel is destroyed.

  • Related