Seri
08/29/2018, 5:24 PMgildor
08/29/2018, 5:27 PMSeri
08/29/2018, 5:42 PMwithoutclass
08/29/2018, 6:21 PMSeri
08/29/2018, 6:44 PMimport kotlinx.coroutines.experimental.channels.*
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking
fun main(args: Array<String>) = runBlocking<Unit> {
// Create the listener
val listener = ConflatedBroadcastChannel<Int>()
// Create the actor
val actor = counterActor(listener)
// Send some events
launch{
repeat(5) {
actor.send(Event.Increment)
delay(250)
}
repeat(5) {
actor.send(Event.Decrement)
delay(250)
}
actor.close()
}
// Print out the counter
for (i in listener.openSubscription()) {
println("The counter is $i")
}
}
fun counterActor(counterReceiver: SendChannel<Int>) = actor<Event> {
var counter = 0
for (msg in channel) {
counter = when (msg) {
is Event.Increment -> counter + 1
is Event.Decrement -> counter - 1
}.also {
counterReceiver.send(it)
}
}
counterReceiver.close()
}
sealed class Event {
object Increment: Event()
object Decrement: Event()
}
withoutclass
08/29/2018, 6:45 PM