Created
August 1, 2023 14:31
-
-
Save hieuwu/8067edb4e4d58cd256e032adaa00cf5c 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
@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