https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Travis Griggs

02/23/2024, 1:00 AM
I've got a fun
passkeysSync
which I dutifully made a suspend fun, because I updated our settings story to use the newer DataStore stuff. In some of my code, I have very good place to grab a scope and do a launch with this guy. But I'm also using an imported library, HiveMQ and using it's "asynchronous API". I register a message handler callback with the async client, and in some cases, I need to run this passkeysSync function. Is a time when it's OK to use
runBlocking { }
around my suspend fun? Or is there some other technique/pattern I ought to be using in this case?
j

jw

02/23/2024, 1:14 AM
Send
Unit
into a conflated channel from the callback. Have a coroutine looping on the channel and running the sync.
👀 1
g

gildor

02/28/2024, 4:57 AM
runBlocking is fine as soon as it's fine block the theread where you do it it's not an issue for coroutines that you wrap them with runBlocking, it's potential issue for a code which you block In general, if you have a code which has another asyncronous API, the best solution is to wrap it to coroutines (similar how official integration works), there are a couple of techniques for this, the most common one is to use
suspendCancellableCoroutine
builder It would be helpful if you share example of code what you are trying to do
g

gildor

02/29/2024, 7:14 AM
Yep, you should write an adapater It's more complicated, because as I see you need not only suspend adapter, but also flow adapter, which also not an issue I would really sugggest to invest into writing Flow adapters for those APIs, it will make integration so much easier and safer
I also don't agree that runBlocking is the best solution here, it's a lot better to make HimeMQ adapter, same way as it works for RxJava or Reactor: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-reactive/
Whole code there also can be rewritten in more safe way, if you return Flow, instead of passing callback, but it's additional change not directly related to your original question
Even more, as I see Mqtt3AsyncClient actually already has Rx API, so you can just use it and just immediately call .asFlow()