gpt4 book ai didi

scala - 使用 actor 的可中断循环模式

转载 作者:行者123 更新时间:2023-12-04 11:30:19 27 4
gpt4 key购买 nike

我正在设计一个从无限流中消耗项目的actor,并且需要一种方法来控制它何时开始和停止使用消息。是否有一个共同的模式来实现像这样的 Actor 的可中断循环?我正在考虑让我的 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"
}
}
}

这是处理事情的最佳方式吗?

谢谢!

最佳答案

也许这样编码:

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
}

干杯,

关于scala - 使用 actor 的可中断循环模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5626285/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com