Skip to content

Instantly share code, notes, and snippets.

@lampard-android
Created November 15, 2021 17:21
Show Gist options
  • Save lampard-android/904534602f569c471e556ce5a9203d4f to your computer and use it in GitHub Desktop.
Save lampard-android/904534602f569c471e556ce5a9203d4f to your computer and use it in GitHub Desktop.
ListRestaurantsViewModel.kt
package com.setel.demo.list.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.setel.demo.data.ResponseData
import com.setel.demo.data.RestaurantModel
import com.setel.demo.repository.RestaurantRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.*
import javax.inject.Inject
@HiltViewModel
class ListRestaurantsViewModel @Inject constructor(
private val repository: RestaurantRepository,
private val dispatcher: CoroutineDispatcher = Dispatchers.Default
) :
ViewModel() {
private val _listRestaurantLiveData = MutableLiveData<ResponseData<RestaurantModel>>()
val listRestaurantLiveData: LiveData<ResponseData<RestaurantModel>>
get() = _listRestaurantLiveData
fun getAllRestaurants() {
viewModelScope.launch(dispatcher) {
_listRestaurantLiveData.postValue(ResponseData.Loading)
repository.getAllRestaurants().let {
if (it.isSuccessful) {
it.body()?.let { rsModel ->
rsModel.restaurants.forEach { it.parseOperatingDay() }
_listRestaurantLiveData.postValue(ResponseData.Success(rsModel))
} ?: kotlin.run {
_listRestaurantLiveData.postValue(ResponseData.Error(Exception("Empty Response")))
}
} else {
_listRestaurantLiveData.postValue(
ResponseData.Error(
Exception(
it.errorBody().toString()
)
)
)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment