Miguel Vargas
07/01/2020, 6:34 PMprivate suspend fun outerSuspend() {
timer(period = 10) {
innerSuspend() // Error: Suspend functions can be only called within coroutine body
}
}
It works if I create a new CoroutineScope inside the function block
private suspend fun outerSuspend() {
timer(period = 10) {
CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch {
innerSuspend()
}
}
}
Is there a way to use the outer scope in the inner block?octylFractal
07/01/2020, 6:35 PMtimer
be inline
or suspend
itselfstreetsofboston
07/01/2020, 7:51 PMprivate suspend fun outerSuspend() = coroutineScope {
timer(period = 10) {
launch { innerSuspend() }
}
}
Because creating a new CoroutineScope
, like in your original example’s solution, breaks cancellation/structured-concurrency.octylFractal
07/01/2020, 7:52 PMtimer
runBlocking
it to do that (or runInterruptible
in more recent versions)streetsofboston
07/01/2020, 7:53 PMgildor
07/01/2020, 11:55 PMstreetsofboston
07/02/2020, 2:49 AMwhile (isActive) {
innerSuspend()
delay(periodInMillis)
}
is a straightforward solution.gildor
07/02/2020, 3:32 AMjulian
07/02/2020, 4:08 AMoctylFractal
07/02/2020, 4:10 AMtimer
function was intended to cancel / interrupt / measure the inner block, it would not do so properly because launch
immediately returns in this casejulian
07/02/2020, 5:57 AM