// Solution 0: Disable the sort buttons when any sort is running class ProductsViewModel(val productsRepository: ProductsRepository): ViewModel() { private val _sortedProducts = MutableLiveData>() val sortedProducts: LiveData> = _sortedProducts private val _sortButtonsEnabled = MutableLiveData() val sortButtonsEnabled: LiveData = _sortButtonsEnabled init { _sortButtonsEnabled.value = true } /** * Called by the UI when the user clicks the appropriate sort button */ fun onSortAscending() = sortPricesBy(ascending = true) fun onSortDescending() = sortPricesBy(ascending = false) private fun sortPricesBy(ascending: Boolean) { viewModelScope.launch { // disable the sort buttons whenever a sort is running _sortButtonsEnabled.value = false try { _sortedProducts.value = productsRepository.loadSortedProducts(ascending) } finally { // re-enable the sort buttons after the sort is complete _sortButtonsEnabled.value = true } } } }