Created
August 29, 2021 03:44
-
-
Save widiarifki/a3c930ef48f4e206a20c8ddc3fed1ead to your computer and use it in GitHub Desktop.
This gist is part of https://github.com/widiarifki/android-playground/tree/master/compose
This file contains 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 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