uhe
03/17/2017, 2:26 PMval channel = Channel<Int>()
launch(CommonPool) {
delay(50)
println("Closing and flushing channel")
channel.closeAndFlush()
}
(0..3).map { number ->
launch(context) {
println("Sending $number")
channel.send(number)
println("$number sent")
}
}.forEach { it.join() }
println("Done!")
which prints:
Sending 0
Sending 1
Sending 2
Sending 3
Closing and flushing channel
0 sent
1 sent
2 sent
3 sent
Done!
elizarov
03/17/2017, 2:43 PMuhe
03/17/2017, 3:07 PMJob
, but a custom domain job) and processes them in order (in the background). The result of the job should be sent back to the user. Like that:
class ActorJobMessage(val job: BaseJob, val resultChannel: SendChannel<Result>)
private fun createActor() {
actor = actor(CommonPool) {
for (message in this) {
val result = message.job.process()
message.resultChannel.sendSafely(result)
}
}
}
suspend private fun schedule(job: BaseJob): Result {
val resultChannel = Channel<Result>()
try {
actor.sendOrNull(ActorJobMessage(job, resultChannel)) ?: return Error(701, "Cannot schedule jobs right now.")
return resultChannel.receive()
} finally {
resultChannel.closeAndFlush()
}
}
schedule
is cancelled before result.receive
sendSafely
just ignores `ClosedSendChannelException`s)kevinherron
03/17/2017, 3:11 PMuhe
03/17/2017, 3:13 PMelizarov
03/17/2017, 3:25 PMcancel
an actor if you must terminate it without processing the rest of its inboxclose
is for “graceful” terminationuhe
03/17/2017, 3:27 PMclose
, however, affects the SendChannel
that is created for each user.