Is there a way to run suspending code in blocking ...
# coroutines
k
Is there a way to run suspending code in blocking mode reliably?
runBlocking
seems to give up immediately it encounters an interrupt, leaving the suspending function in a possibly corrupt mode. Or maybe I'm only overthinking this? 🤔
e
What do you mean? Can you provide an example?
k
Hi @elizarov. I have a setup like:
Copy code
suspend fun doStuff() {
  // Call suspending API method
  someDb.use {
    // write stuff to db
  }
}
Now, I need to run this function in blocking mode. Currently, I'm simply doing:
Copy code
fun blockingFun() = runBlocking {
  doStuff()
}
...but there is a time frame after which the thread could be interrupted. Is there a way to guarantee
doStuff
runs to completion before
runBlocking
throws interrupted exception? PS: I was on mobile and didn't get a notification, would have responded to this earlier
e
One solution is to do this:
Copy code
fun blockingFun() = runBlocking {
    run (NonCancellable) { doStuff() }
}
What it does is that
runBlocking
will throw
InterrupedException
if interrupted, but it will not cancel the execution of
doStuff
— it will continue to work even after the
runBlocking
returns with exception (it will execute as if working with
Unconfined
dispatcher)
If that does not solve your problem, then it is quite straightforward to implement some kind of
runBlockingUninterruptibly { … }
or
runBlocking(interruptible=false) { … }
k
Yes. I thought about using
run(NonCancellable)
, but I am using some resources that might get closed once
runBlocking
returns I am currently using a
runSilentBlocking
which basically wraps run blocking in a try/catch, but yes, I'll look into tweaking
runBlocking
to make it run uninterruptibly
e
You are welcome to submit a pull request for kotlinx.coroutines project or, at least, create an issue (in its github tracker)