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!
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With