https://kotlinlang.org logo
Title
p

pawelbochenski

12/19/2018, 7:18 AM
Hi, I have method with a callback, that will be called more then once. how to wrap it into coroutine?
b

bdawg.io

12/19/2018, 7:23 AM
Do you need the result of each time the callback is invoked?
p

pawelbochenski

12/19/2018, 7:24 AM
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

dave08

12/19/2018, 7:27 AM
suspendCancellableCoroutine { }
see the coroutines KEEP in the repo, it explains how to wrap callbacks.
p

pawelbochenski

12/19/2018, 7:38 AM
suspendCancellableCoroutine will not work, callback will be called more than once
g

gildor

12/19/2018, 7:39 AM
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

dave08

12/19/2018, 7:42 AM
Perhaps
produce { }
?
g

gildor

12/19/2018, 7:42 AM
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

pawelbochenski

12/19/2018, 7:48 AM
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

gildor

12/19/2018, 7:51 AM
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

pawelbochenski

12/19/2018, 7:55 AM
ok thanks a lot 🙂
s

streetsofboston

12/19/2018, 1:03 PM