https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

Norbi

12/11/2023, 10:05 PM
Is there a way to implement the following?
Copy code
fun main() {
    runBlocking {
        first()
    }
}

suspend fun first() {
    second()
}

fun second() {
    // How? :(
    // runBlocking { // Would be incorrect based on the docs...
        third() // Compilation error: Suspend function 'third' should be called only from a coroutine or another suspend function
    // }
}

suspend fun third() {
}
p

Patrick Steiger

12/12/2023, 12:54 AM
Make second suspend?
n

Norbi

12/12/2023, 9:47 AM
Make second suspend?
Yes 😄 I tried to simplify my problem, the related functions are in an external dependency I don't want to modify. Let's suppose that only
main()
and
third()
are my functions. I feel that the restriction of using
runBlocking()
in a coroutine is a major problem in the API, I often struggle because many library functions are non-suspend but I have to call suspend library functions from them 😕.
s

Sam

12/12/2023, 10:33 AM
Assuming
second()
doesn't need to wait for
third()
to complete, the answer is to use a coroutine scope to launch a new coroutine.
Copy code
fun second() {
    myScope.launch { third() }
}
As for where
myScope
comes from, that depends on your app.
🙏 1