Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka: Send a future message to an Actor

Tags:

scala

akka

I have the following code inside an Actor

def receive = {
    case All() => {
        val collection: BSONCollection = db("ping")
        val future:Future[List[Ping]] = collection.find(BSONDocument()).cursor[Ping].toList()
        val zender = sender
        future onComplete {
            case Success(list) => zender ! list
            case Failure(throwable) => zender ! List()
        }
    }
}

I don't like how I have to use the onComplete function to send the result back to the sender actor. I'd like to know if it is possible to convert it into something like this:

def receive = {
    case All() => {
        val collection: BSONCollection = db("ping")
        val future:Future[List[Ping]] = collection.find(BSONDocument()).cursor[Ping].toList()
        "sender ! future" // one option
        "future.map( list => sender ! list)" //Another option. I know it's not map, but maybe another function        
    }
}

I feel that this flows better with future chaining.

like image 735
Luciano Avatar asked May 06 '13 14:05

Luciano


People also ask

How can I send a message to an actor in Akka?

1) Akka Actor tell() Method It works on "fire-forget" approach. You can also use ! (bang) exclamation mark to send message. This is the preferred way of sending messages.

How do you send a message to an actor?

If you can send private messages, do so with a friendly, polite request for contact. Respectfully tell the celebrity in your message how you feel about them and why they are important to you. Making your message personal may improve your chances of being contacted.

What is future in Akka?

Introduction. In the Scala Standard Library, a Future is a data structure used to retrieve the result of some concurrent operation. This result can be accessed synchronously (blocking) or asynchronously (non-blocking). To be able to use this from Java, Akka provides a java friendly interface in akka.

How do you use future in Scala?

Future. Future represents a result of an asynchronous computation that may or may not be available yet. When we create a new Future, Scala spawns a new thread and executes its code. Once the execution is finished, the result of the computation (value or exception) will be assigned to the Future.


2 Answers

You can use the pipe pattern for that. Just import akka.pattern.pipe and then you'll be able to pipe messages from futures to actors with future pipeTo actor.

like image 73
drexin Avatar answered Oct 26 '22 18:10

drexin


If you want to have an empty list when failure happens, you probably want to have chained calls of "recover" and "pipeTo".

like image 23
Endre Varga Avatar answered Oct 26 '22 19:10

Endre Varga