Skip to content

Instantly share code, notes, and snippets.

@kozmi55
Last active Aug 15, 2021
Embed
What would you like to do?
CarListViewModel.kt
@HiltViewModel
class CarListViewModel @Inject constructor(
private val carDataProvider: CarDataProvider
) : ViewModel() {
val data: LiveData<List<ItemViewModel>>
get() = _data
private val _data = MutableLiveData<List<ItemViewModel>>(emptyList())
init {
loadData()
}
private fun loadData() {
// This is a coroutine scope with the lifecycle of the ViewModel
viewModelScope.launch {
// getCarListData() is a suspend function
val carList = carDataProvider.getCarListData()
val carsByMake = carList.groupBy { it.make }
val viewData = createViewData(carsByMake)
_data.postValue(viewData)
}
}
private fun createViewData(carsByMake: Map<String, List<CarData>>): List<ItemViewModel> {
val viewData = mutableListOf<ItemViewModel>()
carsByMake.keys.forEach {
viewData.add(HeaderViewModel(it))
val cars = carsByMake[it]
cars?.forEach { car: CarData ->
val item = if (car.isAd) {
CarAdViewModel(car.make, car.model, car.price)
} else {
CarListingViewModel(car.make, car.model, car.price)
}
viewData.add(item)
}
}
return viewData
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment