Title
k

kingsley

04/11/2017, 8:20 PM
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

elizarov

04/11/2017, 8:21 PM
What do you mean? Can you provide an example?
k

kingsley

04/12/2017, 10:17 AM
Hi @elizarov. I have a setup like:
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:
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

elizarov

04/12/2017, 10:45 AM
One solution is to do this:
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

kingsley

04/12/2017, 10:49 AM
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

elizarov

04/12/2017, 12:02 PM
You are welcome to submit a pull request for kotlinx.coroutines project or, at least, create an issue (in its github tracker)