spieden
spieden

Reputation: 1269

Pattern for interruptible loops using actors

I'm designing an actor that consumes items from an endless stream, and need a way to control when it starts and stops using messages. Is there a common pattern for implementing interruptible loops like this with actors? I was thinking of just having my actor send messages to itself. Something like (pseudo 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"
    }
  }
}

Is this the best way to go about things?

Thanks!

Upvotes: 7

Views: 1810

Answers (1)

Viktor Klang
Viktor Klang

Reputation: 26579

Perhaps encoded like this:

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
}

Cheers,

Upvotes: 9

Related Questions