5.13
8. 实现商品销售功能
在本部分中,您将扩展应用的功能以实现销售功能。此更新涉及以下任务:
- 为 DAO 函数添加测试以更新实体。
- 在
ItemDetailsViewModel中添加一个函数以减少数量并更新应用数据库中的实体。 - 如果数量为零,停用 Sell 按钮。
- 在
ItemDaoTest.kt中,添加一个名为daoUpdateItems_updatesItemsInDB()且不带参数的函数。使用@Test和@Throws(Exception::class)对其进行注解。
@Test
@Throws(Exception::class)
fun daoUpdateItems_updatesItemsInDB()
- 定义函数并创建
runBlocking代码块。在其中调用addTwoItemsToDb()。
fun daoUpdateItems_updatesItemsInDB() = runBlocking {
addTwoItemsToDb()
}
- 调用
itemDao.update,使用不同的值更新两个实体。
itemDao.update(Item(1, "Apples", 15.0, 25))
itemDao.update(Item(2, "Bananas", 5.0, 50))
- 使用
itemDao.getAllItems()检索实体。将其与更新后的实体进行比较并断言。
val allItems = itemDao.getAllItems().first()
assertEquals(allItems[0], Item(1, "Apples", 15.0, 25))
assertEquals(allItems[1], Item(2, "Bananas", 5.0, 50))
- 确保完成后的函数如下所示:
@Test
@Throws(Exception::class)
fun daoUpdateItems_updatesItemsInDB() = runBlocking {
addTwoItemsToDb()
itemDao.update(Item(1, "Apples", 15.0, 25))
itemDao.update(Item(2, "Bananas", 5.0, 50))
val allItems = itemDao.getAllItems().first()
assertEquals(allItems[0], Item(1, "Apples", 15.0, 25))
assertEquals(allItems[1], Item(2, "Bananas", 5.0, 50))
}
- 运行测试并确保测试通过。
在 ViewModel 中添加一个函数
- 在
ItemDetailsViewModel.kt的ItemDetailsViewModel类中,添加一个名为reduceQuantityByOne()且不带参数的函数。
fun reduceQuantityByOne() {
}
- 在该函数内,使用
viewModelScope.launch{}启动协程。
注意:您必须在协程内运行数据库操作。
import kotlinx.coroutines.launch
import androidx.lifecycle.viewModelScope
viewModelScope.launch {
}
- 在
launch代码块内,创建一个名为currentItem的val,并将其设置为uiState.value.toItem()。
val currentItem = uiState.value.toItem()
uiState.value 的类型为 ItemUiState。您可以使用扩展函数 toItem() 将其转换为 Item 实体类型。
- 添加
if语句以检查quality是否大于0。 - 对
itemsRepository调用updateItem()并传入更新后的currentItem。使用copy()更新quantity值,使函数如下所示:
fun reduceQuantityByOne() {
viewModelScope.launch {
val currentItem = uiState.value.itemDetails.toItem()
if (currentItem.quantity > 0) {
itemsRepository.updateItem(currentItem.copy(quantity = currentItem.quantity - 1))
}
}
}
- 返回到
ItemDetailsScreen.kt。 - 在
ItemDetailsScreen可组合项中,转到ItemDetailsBody()函数调用。 - 在
onSellItemlambda 中,调用viewModel.reduceQuantityByOne()。
ItemDetailsBody(
itemUiState = uiState.value,
onSellItem = { viewModel.reduceQuantityByOne() },
onDelete = { },
modifier = modifier.padding(innerPadding)
)
- 运行应用。
- 在 Inventory 界面上,点击列表元素。当 Item Details 界面显示时,点按 Sell,您会注意到数量值减少了 1。

浙公网安备 33010602011771号