Is it allowed to use `runBlocking()` in my applica...
# coroutines
n
Is it allowed to use
runBlocking()
in my application if the
main()
function itself is
suspend
?
j
Without more details, it's hard to say, so the answer is the classic "it depends". For instance, do you intend to use it in a blocking callback from a java library? That could be fine
🙏 1
n
"do you intend to use it in a blocking callback from a java library" - from Kotlin code, but yes...
c
Can you give more information on what you're doing? What's important is never calling
runBlocking
from within a call stack which already has `suspend`; otherwise, you get two completely unrelated coroutine contexts.
n
never calling
runBlocking
from within a call stack which already has
suspend
Then the
suspend main()
solution won't be correct 😞 I have some code that creates a Koin container, and when initializing one of the singletons, it calls a
suspend
operation using
runBlocking()
. What I need is to port this to multiplatform code, including Kotlin/JS - and I'm stuck at how to do it... So basically a non-suspend library code calls my code where I need to call a suspend function. I think this is not possible to do in Kotlin/JS, so I try to find some alternative...
j
basically a non-suspend library code calls my code where I need to call a suspend function
Then it depends on what the library expects. Does it expect the work to be complete when the function returns? If not, then you might get away by launching an asynchronous piece of code to do the work, and return immediately. But if the caller needs a guarantee that the code has been executed before the function returns, then it's going to be more complicated.
n
Does it expect the work to be complete when the function returns?
Unfortunatelly, yes. That's why I started to "hack" the whole bootstrap process by using a
suspend main()
, so making the
coroutineScope()
function available in nested non-suspend code as well. But probably I have to do a larger restructuring 😞 Thanks.
c
What are you using Koin for, exactly? It may be easier to just drop it and use regular variables instead, that you can initialize in the order you want in the
suspend main
function.
n
What are you using Koin for, exactly?
I use it extensively for (multiplatform) modularization and as a "DI framework" - so I can't drop it easily... but thanks for the idea.