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

标签 kotlin reactive-programming actor

有个概念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/

相关文章:

android - Ktlint 与 lint 的区别?

java - 如何阻止线程等待 vert.x 中的响应?

scala - 如何处理 Akka 子角色的长时间初始化?

actor - 我的 Akka Actor 的属性是否应该标记为 @volatile?

scala - 在Scala中,什么时候Future比Actor(反之亦然)更合适?

android - 在 kotlin android 中使用 Companion 对象是一个好习惯吗?

kotlin - 如何从注释处理器生成 kotlin 文件?

Android (Kotlin) 无法访问 TableRow 元素的子元素

android - 如何让这段用 RxKotlin 编写的代码块更干净,避免阻塞线程?

swift - RxSwift - 如何在可观察值发生变化但仅发出最后一个值时重试?