spierce7
03/15/2019, 7:28 PMspierce7
03/15/2019, 7:28 PMfun test() {
val channel = BroadcastChannel<Int>(10)
var job = Job()
// Emit 2 values every second
GlobalScope.launch {
var count = 0
while (true) {
delay(500)
channel.send(count++)
}
}
// Create more and more subscribers continually, until they are eventually cancelled below
GlobalScope.launch {
while (true) {
delay(500)
val scope = GlobalScope + job
scope.launch {
for (event in channel.openSubscription()) {
println("Event: $event")
}
}
}
}
// Cancel the job every 5 seconds
GlobalScope.launch(Dispatchers.Main) {
while (true) {
delay(5000)
job.cancel()
job = Job()
println("Cancel")
}
}
}
Dico
03/15/2019, 7:37 PMjob
variable asynchronously.spierce7
03/15/2019, 7:40 PMDico
03/15/2019, 7:41 PMDico
03/15/2019, 7:42 PMconsumeEach
did but it will be removedDico
03/15/2019, 7:42 PMSiebelsTim
03/15/2019, 7:43 PM// Create more and more subscribers continually, until they are eventually cancelled below
GlobalScope.launch {
while (true) {
delay(500)
val scope = GlobalScope + job
scope.launch {
val openSubscription = channel.openSubscription()
try {
for (event in openSubscription) {
println("Event: $event")
}
} finally {
openSubscription.cancel()
}
}
}
}
That works for me.Dico
03/15/2019, 7:44 PMclose()
rightSiebelsTim
03/15/2019, 7:44 PMBroadcast channel is a non-blocking primitive for communication between the sender and multiple receivers that subscribe for the elements using openSubscription function and unsubscribe using ReceiveChannel.cancel function.https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-broadcast-channel/
Dico
03/15/2019, 7:44 PMspierce7
03/15/2019, 7:47 PMtry / finally
works. This is extremely inconvenient though. Is there a more convenient way to accomplish this?Dico
03/15/2019, 7:55 PMconsumeEach
Dico
03/15/2019, 7:57 PMspierce7
03/15/2019, 8:03 PMspierce7
03/15/2019, 8:28 PM