Last active
May 23, 2019 09:52
-
-
Save objcode/abdf2053babc6ad82d452c55e0c2b981 to your computer and use it in GitHub Desktop.
Disable the buttons while a sort is running
This file contains hidden or 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
// Solution 0: Disable the sort buttons when any sort is running | |
class ProductsViewModel(val productsRepository: ProductsRepository): ViewModel() { | |
private val _sortedProducts = MutableLiveData<List<ProductListing>>() | |
val sortedProducts: LiveData<List<ProductListing>> = _sortedProducts | |
private val _sortButtonsEnabled = MutableLiveData<Boolean>() | |
val sortButtonsEnabled: LiveData<Boolean> = _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 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment