Luciano
Luciano

Reputation: 8582

Akka: Send a future message to an Actor

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.

Upvotes: 14

Views: 7949

Answers (2)

Endre Varga
Endre Varga

Reputation: 1863

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

Upvotes: 10

drexin
drexin

Reputation: 24413

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.

Upvotes: 32

Related Questions