Norbi
11/04/2021, 8:15 AMfun main() {
runBlocking {
suspendFun()
}
}
suspend fun suspendFun() {
normalFun()
}
fun normalFun() {
val runningInCoroutine = ???
check(!runningInCoroutine)
runBlocking {
...
}
}
Joffrey
11/04/2021, 8:21 AMrunBlocking
is a way to give up when you have no choice but to bridge a blocking API with suspending one. So you shouldn't really use it from any non suspend function, you should try other options first.
Normally in the case you're showing, you should try to make your own function suspend, and go up the stack until you hit a roadblock. If you end up in a place where you don't control the caller, you can assume it's not using coroutines and use runBlocking
.ephemient
11/04/2021, 8:34 AMrunBlocking
at specific entry points (such as main
), which then avoids this issue entirely.yschimke
11/04/2021, 8:48 AMephemient
11/04/2021, 8:51 AMephemient
11/04/2021, 8:51 AMfun main()
on android anyway :Dephemient
11/04/2021, 9:05 AMrunBlocking()
on Android, so that you could enable a similar sort of runtime check, but unfortunately it doesn't look like there's a built-in extension point to do that. could be worth filing a feature requestAdam Powell
11/04/2021, 1:36 PMrunBlocking
on Android and you're not doing it in a method annotated @Test
you're probably on the wrong path.Aidan Low
11/04/2021, 3:45 PMephemient
11/04/2021, 3:55 PMJoffrey
11/04/2021, 3:55 PMrunBlocking
. However, if it's ok for the Java thread to just start something asynchronous that returns immediately, your Kotlin helper could launch the coroutine in a particular coroutine scope.Aidan Low
11/04/2021, 3:58 PMrunBlocking
.