如果从非可挂起的块调用,则Android协程范围会丢失

时间:2019-04-18 20:25:45

标签: android coroutine

我正在尝试从lambda表达式执行可挂起的函数:

fun executeAll() {
     // non-ui thread required for this task. Retain the jobId and clear it once the VM is destroyed
     jobId = launch(Dispatchers.IO) {
         try {
             // execute all queries in one transaction
             appDatabase.runInTransaction {
                 // !! THIS --> "Suspension functions can be called only with coroutine body"
                 runQueries()
             }
         }
         catch (e: Exception) {
         }
     }
 }

 private suspend fun runQueries() {
     userRepository.deleteAll()
     userRepository.insertAll(users)
 }

 override fun onCleared() {
     super.onCleared()
     jobId?.cancel()
 }

执行runQueries()给我一个错误,因为它不是从协程体内调用的。但是我该如何解决呢?我已经在叫launch(Dispatchers.IO)。我应该创建一个新的协程工作吗?我要做的是将我包裹在runBlocking块中:

runBlocking {
   runQueries()
}

但是我读到我不应该在生产中使用runBlocking,因为这是Kotlin团队的错误,现在将其删除已经为时已晚。

1 个答案:

答案 0 :(得分:3)

您必须将runInTransaction更改为withTransaction