Skip to content

Instantly share code, notes, and snippets.

@FannyDemey
Created September 21, 2023 13:16
Show Gist options
  • Save FannyDemey/d996129845e67690460d913f7c23455e to your computer and use it in GitHub Desktop.
Save FannyDemey/d996129845e67690460d913f7c23455e to your computer and use it in GitHub Desktop.
class BrowseViewModel : ViewModel() {
private val _products: MutableStateFlow<List<Product>> = MutableStateFlow(emptyList())
val products: StateFlow<List<Product>> = _products.asStateFlow()
init {
viewModelScope.launch {
delay(1000)
_products.value = FakeDataSource.ALL_PRODUCTS
}
}
fun add(productId: String) {
val newProductList = _products.value.map { product ->
if (product.id == productId) {
return@map product.copy(quantity = product.quantity + 1)
} else {
return@map product
}
}
_products.value = newProductList
}
fun remove(productId: String) {
val newProductList = _products.value.map { product ->
if (product.id == productId) {
return@map product.copy(quantity = product.quantity - 1)
} else {
return@map product
}
}
_products.value = newProductList
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment