我正在设计一个消耗来自无穷无尽的流中的项目的actor,并且需要一种方法来控制它何时开始和停止使用消息。是否有与演员一起实现这样的可中断循环的通用模式?我在考虑让我的演员向自己发送消息。像(伪Scala):
class Interruptible extends Actor {
val stream: Stream
val running: boolean
def receive = {
case "start" => {
running = true
consumeItem
}
case "stop" => {
running = false
}
case "consumeNext" => consumeItem
}
def consumeItem {
if (running) {
stream.getItem
this ! "consumeNext"
}
}
}
这是最好的办法吗?
谢谢!
答案 0 :(得分:8)
也许编码如下:
class Interruptible extends Actor {
val stream: Stream
def inactive: Receive = { // This is the behavior when inactive
case "start" =>
self become active
}
def active: Receive = { // This is the behavior when it's active
case "stop" =>
self become inactive
case "next" =>
doSomethingWith(stream.getItem)
self ! "next"
}
def receive = inactive // Start out as inactive
}
干杯,