有个概念actor
在 Kotlin 协程库中:
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)
}
}
}
文档说
A simple actor can be written as a function, but an actor with a complex state is better suited for a class.
什么是在 Kotlin 中定义为类的 Actor 的好例子?
最佳答案
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)
}
}
该示例取自 here .
关于kotlin - 如何在 Kotlin 中将 actor 定义为一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56644916/