How to define actor as a class in Kotlin
Asked Answered
P

1

6

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?

Pentadactyl answered 18/6, 2019 at 8:34 Comment(0)
I
4
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.

Inculpable answered 16/10, 2019 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.