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

pavel.v

04/14/2019, 9:09 AM
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

tseisel

04/14/2019, 9:27 AM
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

Paul Woitaschek

04/14/2019, 9:53 AM
Did you check out flow yet?
🚫 1
p

pavel.v

04/14/2019, 9:58 AM
@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

tseisel

04/14/2019, 10:30 AM
@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

Paul Woitaschek

04/14/2019, 11:45 AM
Check the docu of flowViaChannel @tseisel
s

streetsofboston

04/14/2019, 1:03 PM
What about providing a
CoroutineScope
and wrapping the call to
send
inside a
launch
?
t

tseisel

04/14/2019, 3:32 PM
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).
5 Views