How to keep an active subscription to the channel?...
# coroutines
a
How to keep an active subscription to the channel? Documentation doesn’t mention BroadcastChannel/ConflatedBroadcastChannel and I need to keep active subscription to one of those
a
Looks like it doesn’t stay active because I get data only once
Copy code
myBroadcastChannel.openSubscription().consume {
                for (value in this) {
                    process(value)
                }
            }
s
What does your code look like?
ah, use consumeEach
a
Tried, same result
I have a callback when data changes in database, and I send it to a broadcast channel
I listen to the channel in my presenter
I see that data changes and event is pushed to brodscast, but subscription doesn’t kick in anymore
only once
s
Something like this should work:
Copy code
for (i in listener.openSubscription()) {
    println("The counter is $i")
}
or
Copy code
listener.consumeEach {
    println("The counter is $it")
}
a
I think I tried all options already, same result
it’s quite confusing though, with so many variants to subscribe to coroutine
s
I had a sample script I was working through yesterday that used ConflatedBroadcastChannel: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1535568252000100?thread_ts=1535563475.000100&cid=C1CFAFJSK
a
Hmm My code is now spread among several classes but general idea is, I create
ConflatedBroadcastChannel()
and save it into variable. Then I subscribe to my database updates and when I get data I send it to that channel On the client side, I get what’s in that variable, and try to subscribe
So first time I get data from database subscription works fine
but when I change and get updates, subscription to broadcast doesn’t kick in anymore
Debugging, I see that data is pushed to the correct broadcastChannel
ok, I fixed it
thanks for ideas 😃
It was running in
async
coroutine and forgot to do
await()
s
ah, alright!
l
@aaverin Remember to use
withContext
in place of
async
whenever possible (i.e. as long as you don't need to parallelize work in a coroutine)