Last active
May 23, 2019 09:52
-
-
Save objcode/05477963bed85d0afed8f679803c6986 to your computer and use it in GitHub Desktop.
Implement a one shot request (ViewModel)
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
class ProductsViewModel(val productsRepository: ProductsRepository): ViewModel() { | |
private val _sortedProducts = MutableLiveData<List<ProductListing>>() | |
val sortedProducts: LiveData<List<ProductListing>> = _sortedProducts | |
/** | |
* 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 { | |
// suspend and resume make this database request main-safe | |
// so our ViewModel doesn't need to worry about threading | |
_sortedProducts.value = | |
productsRepository.loadSortedProducts(ascending) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment