mercredi 25 avril 2018

Good Scala pattern to consume from a Queue until there are no more messages?

I have a queue of N messages dispatched by an Actor, I want to consume them all. The actor will return either a Message type or a NoMessages type if the queue is empty.

I came up with this but doesn't feel idiomatic, and I'm not sure about how many threads I'm spinning up every time I call consume()?

What is a better way of doing this?

def main(): Unit = {

  val queue = system.actorOf(...)

  def consume(): Unit = {
    ask(queue, Read) foreach {
      case Message(m) => {
        // handle message
        consume()
      }
      case NoMessages =>  {
        system.shutdown()
      }
    }
  }
  consume()
}

Aucun commentaire:

Enregistrer un commentaire