Skip to content

Instantly share code, notes, and snippets.

@kozmi55
Last active August 15, 2021 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kozmi55/0c3e643e2f3a476845a307ad63160bfa to your computer and use it in GitHub Desktop.
Save kozmi55/0c3e643e2f3a476845a307ad63160bfa to your computer and use it in GitHub Desktop.
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