我的活动希望使用Room在我的数据库中插入一个新元素,因此该活动将此任务委托给一个传递Entity对象的ViewModel类。该活动需要数据库自动生成的id的值,以便可以实时更新对象。因此,ViewModel类希望在IO池线程上启动一个协程,该线程使用一个返回新id值的insert Dao方法。最后,我的问题是:如何将协程中的值返回给ViewModel方法?
这是我在ViewModel类中的代码:
//return autogenerated id
fun insert(fiscalcode: Fiscalcode): Int {
CoroutineScope(Dispatchers.IO).launch {
db.fiscalcodeDao().insert(fiscalcode)
//return autogenerated id
}
}发布于 2021-08-16 15:07:45
你不能把挂起的世界和非挂起的世界混在一起。您可以在视图模型中创建一个变量。
val _rowId = MutableStateFlow<Int?>(null)
val rowId: StateFlow<Int>
get() = _rowId
fun insert(fiscalcode: Fiscalcode): Int {
CoroutineScope(Dispatchers.IO).launch {
_rowId.value = db.fiscalcodeDao().insert(fiscalcode)
}
}您可以在您的活动中收集此rowId流。
lifecycleScope.launch {
viewModel.rowId
.flowWithLifecycle(this, Lifecycle.State.STARTED)
.collect { rowId -> ... }
}发布于 2021-08-20 07:01:32
这种做法很糟糕,但根据您的问题,如果您想返回,可以使用runBlocking进行同样的操作
val id = runBlocking {
db.fiscalcodeDao().insert(fiscalcode)
}https://stackoverflow.com/questions/68803890
复制相似问题