Skip to content

Instantly share code, notes, and snippets.

@objcode
Last active May 23, 2019 09:52
Show Gist options
  • Save objcode/05477963bed85d0afed8f679803c6986 to your computer and use it in GitHub Desktop.
Save objcode/05477963bed85d0afed8f679803c6986 to your computer and use it in GitHub Desktop.
Implement a one shot request (ViewModel)
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