Skip to content

Instantly share code, notes, and snippets.

@widiarifki
Created August 29, 2021 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save widiarifki/a3c930ef48f4e206a20c8ddc3fed1ead to your computer and use it in GitHub Desktop.
Save widiarifki/a3c930ef48f4e206a20c8ddc3fed1ead to your computer and use it in GitHub Desktop.
class ShoppingListViewModel(
private val repository: ShoppingItemRepository = ShoppingItemRepository()
) : ViewModel() {
// variables that hold state
var isLoading by mutableStateOf(true)
val shoppingItems: LiveData<List<ShoppingItem>> = getItems()
private fun getItems(): LiveData<List<ShoppingItem>> {
isLoading = true
return Transformations.map(repository.allShoppingItems) { items ->
isLoading = false
items
}
}
// event: add item
fun addItem(item: ShoppingItem) {
viewModelScope.launch(Dispatchers.IO) {
repository.insert(item)
}
}
// event: delete item
fun deleteItem(item: ShoppingItem) {
viewModelScope.launch(Dispatchers.IO) {
repository.delete(item)
}
}
// event: tick/un-tick item
fun toggleTickItem(item: ShoppingItem) {
val updatedItem = item.copy(isTicked = !item.isTicked)
viewModelScope.launch(Dispatchers.IO) {
repository.update(updatedItem)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment