Created
November 15, 2021 17:21
-
-
Save lampard-android/904534602f569c471e556ce5a9203d4f to your computer and use it in GitHub Desktop.
ListRestaurantsViewModel.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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