Hi everyone. I’m trying to convert callback based ...
# coroutines
p
Hi everyone. I’m trying to convert callback based api to coroutines. I have converted simple callbacks like onSuccess onFailure with suspendCoroutine call, but i have one method that notify me when some events happens(it like 10 events), i think about to return channel parameterized by sealed class of event from this method. But i can’t call channel send from inside callback method because it not marked as suspend, should i just call launch from every method?
t
2 alternatives here : send each message with
sendBlocking
(mostly equivalent to
send
wrapped in
runBlocking
), or
offer
. Only use the latter if you don't mind losing some messages if the last received one has not been processed yet, or if your channel has a large capacity
1
👍 1
p
Did you check out flow yet?
🚫 1
p
@tseisel I think 2 solution is what I needed. Am I right that difference between send and offer in situation when channel is full, so message provided by offer will be discarded, and send will just suspend until in channel got free space?
t
@pavel.v you're right. Also, with a capacity of
CONFLATED
,
send
does not suspend and
offer
always returns
true
(but the newly sent message will overwrite previous ones)
@Paul Woitaschek If you have an example of usage for bridging flow to callback API, I a really interested 🙂
p
Check the docu of flowViaChannel @tseisel
s
What about providing a
CoroutineScope
and wrapping the call to
send
inside a
launch
?
t
It looks like a viable alternative if consumers of the channel really are slow, as
sendBlocking
would block the thread issuing the callback (often the main thread).