Я пытаюсь выполнить приостановленную функцию из лямбда-выражения:
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, и было слишком поздно, чтобы удалить ее.