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

aaverin

08/29/2018, 7:33 PM
Is there some kind of
blockingProduce
? I have an async callback that I want to wrap into a channel
d

deviant

08/29/2018, 7:50 PM
why you need blocking? just use ordinary
produce
a

aaverin

08/29/2018, 7:53 PM
it closes before my callback sends any data
d

Dominaezzz

08/29/2018, 8:12 PM
How many times is your callback called by the async function?
Once or n times?
d

deviant

08/29/2018, 8:25 PM
it closes before my callback sends any data
just make a loop with suspension point inside
a

aaverin

08/29/2018, 8:30 PM
I have 3rd party library that would deliver data in async manner into a callback any time data changes in the database
So I need a channel that would deliver me those updates forever while app is running
d

Dominaezzz

08/29/2018, 8:31 PM
I don't think produce should be used then. In a new function just create a channel and send to the channel inside your callback, then return the channel.
a

aaverin

08/29/2018, 8:31 PM
produce is the producing part of the channel, isnt’ it?
something that only sends, but doesn’t receive
d

Dominaezzz

08/29/2018, 8:32 PM
Yes but it won't help you here.
Since your function is non-blocking but not suspending.
a

aaverin

08/29/2018, 8:34 PM
should I use
suspendCoroutine
that would publish into a channel?
d

Dominaezzz

08/29/2018, 8:35 PM
I was just thinking about that but if you use
suspendCoroutine
, you can only call the
Continuation
once, as supposed to multiple times, which is what you need.
Copy code
fun magicAsync(): ReceiveChannel<Item> {
        val ch = Channel(...)
        magic(..., { it -> ch.send(it) })
        return ch
}
👍 1
a

aaverin

08/29/2018, 8:39 PM
Yes, looks like it’s the only way
I’ll try applying it, thanks
3 Views