Skip to content
laforge49 edited this page Aug 25, 2011 · 4 revisions

When you need to send messages to actors while looping over a sequence, you can use LoopSafe.

case class LoopSafe(safe: Safe)

What you need to do is create a subclass of Safe, wrap an instance of it in a LoopSafe message and pass the message to a sequence actor. The sequence actor will pass Safe.func a KVPair for every key/value in the sequence. And within the Safe instance, you can update member variables and send messages to any number of actors. The returning false from func effects a break in the loop.

Here's an example which sums the values of a sequence.

class SumSafe extends Safe {
  var sum = 0

  override def func(target: Actor, msg: AnyRef, rf: Any => Unit)(implicit sender: ActiveActor) {
    val nvPair = msg.asInstanceOf[KVPair[Int, Int]]
    sum += nvPair.value
    rf(true)
  }
}

Test code.

val sumSafe = new SumSafe
val rangeSeq = new Range(1, 4)
Future(rangeSeq, LoopSafe(sumSafe))
println(sumSafe.sum)

Output.

6

LoopSafeTest

Tutorial

Clone this wiki locally