[英]How to define actor as a class in Kotlin
Kotlin協程庫中有一個actor
的概念:
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)
}
}
}
文檔說
一個簡單的actor可以寫成一個函數,但是一個具有復雜狀態的actor更適合於一個類。
什么是在 Kotlin 中定義為類的演員的好例子?
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)
}
}
該示例取自此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.