-
-
Save kozmi55/0c3e643e2f3a476845a307ad63160bfa to your computer and use it in GitHub Desktop.
CarListViewModel.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
@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