Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define actor as a class in Kotlin

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?

like image 704
roman-roman Avatar asked Jun 18 '19 08:06

roman-roman


1 Answers

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.

like image 154
Andrey Avatar answered Oct 16 '22 08:10

Andrey