Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for interruptible loops using actors

Tags:

scala

akka

actor

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!

like image 527
spieden Avatar asked Apr 11 '11 19:04

spieden


1 Answers

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,

like image 59
Viktor Klang Avatar answered Sep 25 '22 08:09

Viktor Klang