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.
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.
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.
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.
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.
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
.
If you want to have an empty list when failure happens, you probably want to have chained calls of "recover" and "pipeTo".
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