Hi All , I have one doubt of my implementation for...
# coroutines
v
Hi All , I have one doubt of my implementation for coroutine using MVVM design. I have simple requirement to fetch the data from a server and show to the screen. I have added kotlin data class(Model) , viewModel , repository and my view(Activity) Below is my Repository code look like Its a separate class
Copy code
suspend fun getDataFromServer(page : Int) = RetrofitBuilderInstance.getDataAPIService.getDetalis(page)
From viewModel I call my repository like this
Copy code
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
Copy code
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.