There is a concept of actor
in Kotlin coroutines library:
fun CoroutineScope.counterActor() = actor<CounterMsg> {
var counter = 0 // actor state
for (msg in channel) { // iterate over incoming messages
when (msg) {
is IncCounter -> counter++
is GetCounter -> msg.response.complete(counter)
}
}
}
The documentation says that
A simple actor can be written as a function, but an actor with a complex state is better suited for a class.
What would be a good example of an actor defined as a class in Kotlin?
class MyActor {
// your private state here
suspend fun onReceive(msg: MyMsg) {
// ... your code here ...
}
}
fun myActorJob(): ActorJob<MyMsg> = actor(CommonPool) {
with(MyActor()) {
for (msg in channel) onReceive(msg)
}
}
The example is taken from here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With