Vishvendu
05/15/2020, 3:31 PMsuspend fun getDataFromServer(page : Int) = RetrofitBuilderInstance.getDataAPIService.getDetalis(page)
From viewModel I call my repository like this
private val repository = DataRepository()
private val viewModelJob = SupervisorJob()
private val viewModelScope = CoroutineScope(IO+viewModelJob)
val mNowPlayingDataLiveData = MutableLiveData<NowPlayingMovies>()
fun DataFromrepository(page :Int){
viewModelScope.launch {
val response = repository.getDataFromServer(page)
withContext(Dispatchers.Main){
if(response.isSuccessful){
mNowPlayingDataLiveData .value = response.body()
}}
}}
And I am observing my data in the Activity like this
mViewModel.DataFromrepository(1)
mViewModel.mNowPlayingDataLiveData.observe(this, Observer {mData ->
println(mData.results)
})
And I am successfully Able to get the data in my UI , but I have seen people use multiple ways to achieve the same kind of logic my doubt is what is the best possible way we can achieve a network call using coroutine ?
Sometime I see some people dont use repository at all they directly created the suspend function in the viewmodel and get the data from server.