【发布时间】:2020-10-09 13:54:46
【问题描述】:
我在玩 Kotlin Flow、Coroutines 和 Room。我正在尝试将数据从我的存储库插入到我的房间数据库中。
插入单个项目时没有问题,但如果我尝试插入项目列表,则执行中止并且控制台记录以下消息:
I/Choreographer: Skipped 47 frames! The application may be doing too much work on its main thread.
我不明白为什么插入操作在主线程上执行,因为根据文档,暂停的 DAO 操作应该始终在 Room 内部启动的协程中执行(最终应该在后台线程上运行)。我还尝试在另一个 Scope 中显式运行插入调用(withContext(Dispatchers.IO) { ... }),但没有区别。
我的代码如下所示:
视图模型:
fun setStateEvent(stateEvent: StateEvent) {
viewModelScope.launch {
when (stateEvent) {
is StateEvent.GetItems -> {
repository.getItems().onEach { dateState ->
_dataState.value = dateState
}.launchIn(viewModelScope)
}
}
}
}
存储库:
suspend fun getItems(): Flow<DataState<List<Item>>> = flow {
emit(DataState.Loading)
try {
val items = itemService.getAllItems()
emit(DataState.Success(items))
itemDao.insertItems(items) // The execution stops here
} catch (e: Exception) {
emit(DataState.Error(e))
}
}
道:
@Insert
suspend fun insertItems(items: List<Item>)
我也尝试调试并找到问题的根源,但我没有运气。如果有人能告诉我出了什么问题,我会很高兴。
【问题讨论】:
标签: android kotlin android-room kotlin-coroutines android-mvvm