Skip to content

Instantly share code, notes, and snippets.

@FannyDemey
Created September 12, 2023 09:46
Show Gist options
  • Save FannyDemey/f0db7dce8f0cc4101c1012484afb6eb2 to your computer and use it in GitHub Desktop.
Save FannyDemey/f0db7dce8f0cc4101c1012484afb6eb2 to your computer and use it in GitHub Desktop.
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.techethic.sandbox.ae.model.FakeDataSource
import com.techethic.sandbox.ae.model.Product
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
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