Thomas Keller
Thomas Keller

Reputation: 6080

Kotlin runBlocking for synchronous legacy calls

I need to interface Coroutine-heavy code with legacy Java code in Android. At one place I need to call a suspend method that queries something from a Room database from Android's main thread. And even though this is highly disregarded (I know, I know), I have to make this call (for now at least) block the main thread.

Problem is, runBlocking { mySuspensionMethod() } might trigger an InterruptedException, as the docs state:

If [the] blocked thread [of runBlocking] is interrupted (see Thread.interrupt), then the coroutine job is cancelled and this runBlocking invocation throws InterruptedException.

I re-read the handling of InterruptedExceptions again and again and clearly you should only do one of two things, throw the exception further or set the interrupted flag for your own thread (Thread.currentThread().interrupt()).

Now I guess handling the exception is a dead-end, as I don't want to throw the exception further (which will result in an app crash) nor do I want to interrupt Android's main thread (which results in god knows what), so the question is, is there any other API that I could use to just make this blocking call and return a result?

Upvotes: 1

Views: 2072

Answers (0)

Related Questions