Hi, we are exposing the same asynchronous API mult...
# coroutines
p
Hi, we are exposing the same asynchronous API multiple times, once using coroutines, and once using RxJava. Because RxJava is a pain and adds complexity for our users, we are also thinking of exposing a synchronous/blocking API, for when performance is not key. There is of course a danger of users calling the new blocking API from within a coroutine. Is there any way we could check for this and warn our users?
r
the JetBrains java-annotations library has an
@Blocking
annotation that can be placed on a method that should not be executed in a non-blocking context. It doesn't give any guarantees of course, but at least IntelliJ would give warnings when calling that method in a non-blocking context, and other static analysis tools could potentially catch it as well.
p
nice one!
thanks
👍 1
Funnily enough, when I tried to add that as a test, it didn't seem to warn me
r
could you verify that the relevant inspection (
Possibly blocking call in non-blocking context
) is indeed active? (see screenshot) also note that it is possible to mark a coroutine dispatcher as a BlockingExecutor, meaning that blocking code is allowed inside a coroutine using that executor (and I think the warning is also not generated for
<http://Dispatchers.IO|Dispatchers.IO>
). Maybe you were using the IO dispatcher for your test?
p
Yes, that inspection is enabled, and I was wrapping the call in
runBlocking
r
apparently it depends on the dispatcher used
p
that's interesting
r
thinking more about it, it actually makes sense... when calling
runBlocking
without specifying a Dispatcher, the coroutine runs single-threaded on the calling thread. So any blocking call you do inside the coroutine would only block the calling thread (like it would when calling the blocking method without using
runBlocking
. However, when you do specify a Dispatcher, like
Dispatchers.Default
in my example above, calling blocking code from that coroutine would lead to blocking a thread that's part of a pool of threads also used for other coroutines, which is a general no-no in coroutine-world... so in that case the warning is justified.
p
So I was trying to short circuit the test, but the analysis was too clever for that.
It does make sense when you put it like that, I'll retest
it does show up now, and it shows when I call the method from a method marked
suspend
and hadn't realised that runBlocking runs in the same thread, I assumed it ran
Dispatchers.Default
so thanks for clearing that up, very useful!
r
great! 👍