Return value from Kotlin coroutines inside a non-suspended function

1.1k views Asked by At

I have a function that I override, and I cannot mark it with suspend.

override fun doSmth(): String

Inside it, I need to introduce a non-blocking delay, so I used kotlinx.coroutines.time.delay inside a coroutine.

override fun doSmth(): String {
    runBlocking {
        GlobalScope.launch {
            delay(1000L)
            val result: String = doAnotherThing()
            // How to return this result from doSmth?
        }
    }
}

How to return this result value to the caller of doSmth()?

1

There are 1 answers

0
Joffrey On

I need to introduce a non-blocking delay

How do you expect this to work from your caller's perspective?

Because of your function's signature, you have to block the calling thread until the String is ready. No matter how complex (or async) you make the internals of the function, the constraint stays: the caller has to synchronously wait.

Using runBlocking here does exactly that: make the caller thread actually block until whatever is inside is done. This is why there is no point in using launch if you wrap the whole contents of runBlocking. Instead, you can simply call doAnotherThing() directly:

override fun doSmth(): String {
    return runBlocking {
        delay(1000L)
        doAnotherThing() // last expression is the return value
    }
}

That being said, if you're blocking the calling thread anyway, why not just use the blocking Thread.sleep() instead?

override fun doSmth(): String {
    Thread.sleep(1000L)
    return doAnotherThing()
}