scala – 使用actor的可中断循环的模式
发布时间:2020-12-16 18:53:05 所属栏目:安全 来源:网络整理
导读:我正在设计一个消耗来自无穷无尽的流中的项目的actor,并且需要一种方法来控制它何时开始和停止使用消息.是否有与演员一起实现这样的可中断循环的通用模式?我在考虑让我的演员向自己发送消息.像(伪 Scala)的东西: class Interruptible extends Actor { val
我正在设计一个消耗来自无穷无尽的流中的项目的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 } 干杯, (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |