Active Object
This design pattern allows a method to be executed in a safe way on another thread. Guess what else is being executed on another thread?
You're totally right: actor()
.
So, it's one of those design patterns that is already built into the language. Or, to be precise, into one of the accommodating libraries.
We've already seen how to send data to actor()
. But how do we receive data from it?
One way is to supply it with a channel for output:
fun activeActor(out: SendChannel<String>) = actor<Int> { for (i in this) { out.send(i.toString().reversed()) } out.close() }
Remember to close the output channel when you're done.
Testing
To test the Active Object pattern, we'll launch two jobs. One will send data to our actor:
val channel = Channel<String>() val actor = activeActor(channel) val j1 = launch { for (i in 42..53) { actor.send(i) } actor.close() }
And another will wait for output on the outbound channel:
val j2 = launch { for (i in channel...