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()
?
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 usinglaunch
if you wrap the whole contents ofrunBlocking
. Instead, you can simply calldoAnotherThing()
directly:That being said, if you're blocking the calling thread anyway, why not just use the blocking
Thread.sleep()
instead?