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 に答える