Evan M.
Evan M.

Reputation: 433

Async callback from Akka Actor

I have an actor that may receive messages from an external system (UDP/TCP). Based on the content of the incoming data, there are cases when I want the actor to call back to a non-aka part of my code.
In other words, I don't want to call and actor with ask and wait for some incoming data but rather be called back asynchronously.
How can I implement this without e.g. closing over the calling object (the trivial would be pass in a callback on creation of ActorRef but this would capture caller)?

Upvotes: 0

Views: 358

Answers (1)

jkinkead
jkinkead

Reputation: 4411

Assuming you have a functional interface handleMessage - that is, a method handleMessage that only accepts immutable data - you can simply wrap it in a Future, run inside the actor's context:

import scala.concurrent.Future

// Inside your actor, this is the implicit execution context holding the thread
// pool the actor executes within. You MUST import this in order for it to be in
// the implicit scope for scala.concurrent.Future.
import context.dispatcher
Future {
  handleMessage(messageData)
  // If you need to know when this completes, send a message to the initiating
  // actor here.
}

Upvotes: 0

Related Questions