Created
September 21, 2023 13:16
-
-
Save FannyDemey/d996129845e67690460d913f7c23455e to your computer and use it in GitHub Desktop.
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 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