如何在 Kotlin 中将 actor 定义为一个类

rom*_*man 6 reactive-programming actor kotlin

actorKotlin 协程库中有一个概念:

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

文档说

一个简单的actor可以写成一个函数,但是一个具有复杂状态的actor更适合一个类。

什么是在 Kotlin 中定义为类的演员的好例子?

And*_*rey 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

该示例取自此处