Abhishek Bansal
03/16/2020, 11:30 AMfun main() = runBlocking<Unit> {
val test = Test()
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
println("Receive 1")
test.getResponseChannel()
.collect { println("Collect 1 $it") }
}
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
println("Receive 2")
test.getResponseChannel()
.collect {
println("Collect 2 $it")
}
}
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
println("Receive 3")
test.getResponseChannel()
.collect {
println("Collect 3 $it")
}
}
println("Sending A")
test.responseChannel.send("A")
println("Sending B")
test.responseChannel.send("B")
println("Sending C")
test.responseChannel.send("C")
}
class Test {
val responseChannel = BroadcastChannel<String>(BUFFERED)
fun getResponseChannel(): Flow<String> {
val channel = responseChannel.openSubscription()
return channel
.consumeAsFlow()
.onCompletion {
println("Cancelled")
channel.cancel()
}
}
}
Here you will see that onCompletion()
and hence “Cancelled” never prints. My requirement is to be able to add and detach observers to a broadcast channel. It that achievable?Dennis
03/16/2020, 11:42 AMDennis
03/16/2020, 11:49 AMAbhishek Bansal
03/16/2020, 11:51 AMAbhishek Bansal
03/16/2020, 11:54 AMDennis
03/16/2020, 12:10 PMDennis
03/16/2020, 12:11 PMAbhishek Bansal
03/16/2020, 12:12 PMReceiveChannel
to my upper layers all the way to ViewModels and call consumeAsFlow
there. Save this channel and call cancel
on collect
.Abhishek Bansal
03/16/2020, 12:14 PMOnCompletion
Dennis
03/16/2020, 12:16 PMAbhishek Bansal
03/16/2020, 12:17 PMviewModelScope
if you are familiar with Android AAC.Dennis
03/16/2020, 12:18 PMAbhishek Bansal
03/16/2020, 12:19 PMDennis
03/16/2020, 12:20 PMAbhishek Bansal
03/16/2020, 12:21 PMAbhishek Bansal
03/16/2020, 2:35 PMcollect
does the trick for me. Its a bit non obvious and convoluted right now but works till I get something better. Thanks for going deep in my problem and all your help.