Hi, I have method with a callback, that will be ca...
# coroutines
p
Hi, I have method with a callback, that will be called more then once. how to wrap it into coroutine?
b
Do you need the result of each time the callback is invoked?
p
yes, there will be some data in callback that I need to handle
I was thinking about Channel, but I don’t know how to wrap it up
d
suspendCancellableCoroutine { }
see the coroutines KEEP in the repo, it explains how to wrap callbacks.
p
suspendCancellableCoroutine will not work, callback will be called more than once
g
Than you need channel, because you cannot use suspend functions to receive stream of events
👆🏼 1
Depends on how this channel should work *buffer or drop events.
Actually you just wrap callback, create a channel and send events to it using
send()
(requires runBlocking, or starting coroutine) or
offer
d
Perhaps
produce { }
?
g
but offer is not suspending function, so have to decide what to do if offer is failed (channel is full)
yes, produce can be used, depends on what do you want as result API
also if callback is asyncronous and you just use offer, you even don’t need produce (produce it’s channel + coroutine), but just a channel and callback
p
Copy code
fun subscribe(topic: String): Channel<String> {
        val channel = Channel<String>()
        client.subscribe(topic) { _, message ->
            channel.offer(message.toString())
        }
        return channel
    }
is this enough?
I guess that callback is asynchronous
g
yes, but be careful, this is rendezvous channel, so if event will not be consumed, next offer will just drop data
as I said, it depends on your use case
if you want get all the events, use buffered channel instead
also you do not handle channel cancellation, if your callback API provides some cancellation APIs you can integrate it with channel
p
ok thanks a lot 🙂
s