我每次添加/删除在Firebase中添加/删除项目的操作完成时都需要显示一条消息。这些是接口中的功能:
suspend fun addItem(item: Item): Response<Unit>
suspend fun deleteItem(item: Item): Response<Unit>
这些是实现:
override suspend fun addItem(item: Item) = try {
itemsRef.add(item).await()
Response.Success(Unit)
} catch (ex: Exception) {
Response.Failure(ex)
}
override suspend fun deleteItem(item: Item) = try {
itemsRef.document(item.id).delete().await()
Response.Success(Unit)
} catch (ex: Exception) {
Response.Failure(ex)
}
在ViewModel中,我称为addItem
并重置这样的操作状态:
class ItemViewModel @Inject constructor(
private val repo: ItemRepository
): ViewModel() {
private val _addItemResponse = MutableStateFlow<Response<String>?>(null)
val addItemResponse: StateFlow<Response<String>?> = _addItemResponse.asStateFlow()
private val _deleteItemResponse = MutableStateFlow<Response<String>?>(null)
val deleteItemResponse: StateFlow<Response<String>?> = _deleteItemResponse.asStateFlow()
fun addItem(item: Item) = viewModelScope.launch {
_addItemResponse.value = Response.Loading
_addItemResponse.value = repo.addItem(item)
}
fun deleteItem(item: Item) = viewModelScope.launch {
_deleteItemResponse.value = Response.Loading
_deleteItemResponse.value = repo.addItem(item)
}
fun resetAddItemState() = _addItemResponse.value?.let {
_addItemResponse.value = null
}
fun resetDeleteItemState() = _deleteItemResponse.value?.let {
_deleteItemResponse.value = null
}
}
在UI内部我使用:
when(val addItemResponse = viewModel.addItemResponse.collectAsStateWithLifecycle().value) {
is Response.Loading -> CircularProgressIndicator()
is Response.Success -> {
Toast.makeText(context, "Added", Toast.LENGTH_LONG).show()
resetAddItemState()
}
is Response.Failure -> Text(addItemResponse.ex)
}
when(val deleteItemResponse = viewModel.deleteItemResponse.collectAsStateWithLifecycle().value) {
is Response.Loading -> CircularProgressIndicator()
is Response.Success -> {
Toast.makeText(context, "Deleted", Toast.LENGTH_LONG).show()
resetDeleteItemState()
}
is Response.Failure -> Text(deleteItemResponse.ex)
}
当我添加一个项目时,显示第一个吐司。如果我删除项目并等待第二个吐司消失,则正确显示第二个吐司。但是,如果我添加一个项目并立即将其删除而不等待第一个吐司消失,则会显示第二个吐司。如何解决这个问题?尝试使用应用程序context
希望它会起作用。