7

我正在设计一个从无尽的流中消耗项目的演员,并且需要一种方法来控制它何时开始和停止使用消息。有没有一种通用的模式可以用演员来实现这样的可中断循环?我正在考虑让我的演员向自己发送消息。类似(伪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"
    }
  }
}

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

谢谢!

4

1 回答 1

9

也许像这样编码:

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
}

干杯,

于 2011-04-12T10:18:53.727 回答