Intermittent loop pattern using actors

I am developing an actor who consumes objects from an endless stream, and he needs a way to control when he starts and stops using messages. Is there a general scheme for implementing discontinuous loops like this with actors? I thought about my actor sending messages to himself. 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 get around things?

Thanks!

+6
source share
1 answer

Perhaps encoded as follows:

 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 active case "stop" => self become inactive case "next" => doSomethingWith(stream.getItem) self ! "next" } def receive = inactive // Start out as inactive } 

Greetings

+8
source

Source: https://habr.com/ru/post/885675/


All Articles