Skip to content

Instantly share code, notes, and snippets.

@hieuwu
Created August 1, 2023 14:31
Show Gist options
  • Save hieuwu/8067edb4e4d58cd256e032adaa00cf5c to your computer and use it in GitHub Desktop.
Save hieuwu/8067edb4e4d58cd256e032adaa00cf5c to your computer and use it in GitHub Desktop.
@HiltViewModel
class ProductListViewModel @Inject constructor(
private val productRepository: ProductRepository,
) : ViewModel() {
private val _productList = MutableStateFlow<List<Product>?>(listOf())
val productList: Flow<List<Product>?> = _productList
private val _isLoading = MutableStateFlow(false)
val isLoading: Flow<Boolean> = _isLoading
init {
getProducts()
}
fun getProducts() {
viewModelScope.launch {
val products = productRepository.getProducts()
_productList.emit(products?.map { it -> it.asDomainModel() })
}
}
fun removeItem(product: Product) {
viewModelScope.launch {
val newList = mutableListOf<Product>().apply { _productList.value?.let { addAll(it) } }
newList.remove(product)
_productList.emit(newList.toList())
// Call api to remove
productRepository.deleteProduct(id = product.id)
// Then fetch again
getProducts()
}
}
private fun ProductDto.asDomainModel(): Product {
return Product(
id = this.id,
name = this.name,
price = this.price,
image = this.image
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment