这是我的做法,在尝试从我的 Room 数据库中删除电话号码时返回一个布尔值。您可以使用相同的模式来完成您想要完成的任务。在我的视图模型中:
private var parentJob = Job()
private val coroutineContext: CoroutineContext get() = parentJob + Dispatchers.Main
private val scope = CoroutineScope(coroutineContext)
suspend fun removePhoneNumber(emailSets: EmailSets, personDetails: PersonDetails) : Boolean {
var successReturn = false
scope.async(Dispatchers.IO) {
val success = async {removePhoneNumbersAsync(emailSets,personDetails)}
successReturn = success.await()
}
return successReturn
}
fun removePhoneNumbersAsync(emailSets: EmailSets, personDetails : PersonDetails):Boolean {
var success = false
try {
val emailAddressContact = EmailAddressContact(emailSets.databaseId, personDetails.id, personDetails.active)
repository.deleteEmailAddressContact(emailAddressContact)
val contact = Contact(personDetails.id, personDetails.personName, personDetails.personPhoneNumber, 0)
repository.deleteContact(contact)
success = true
} catch (exception: Exception) {
Timber.e(exception)
}
return success
}
在我的活动中:
runBlocking {
if (v.tag != null) {
val personDetails = v.tag as PersonDetails
val success = viewModel.removePhoneNumber(emailSets,personDetails)
if (success) {
val parentView = v.parent as View
(parentView as? TableRow)?.visibility = View.GONE
val parentViewTable = parentView.parent as ViewGroup
(parentViewTable as? TableLayout)
parentViewTable.removeView(parentView)
}
}
}