来自Akka Actor的异步回调

时间:2018-04-30 20:06:10

标签: scala akka

我有一个可以从外部系统(UDP / TCP)接收消息的actor。根据传入数据的内容,有些情况下我希望演员回调我的代码的非代表部分。
换句话说,我不想用ask调用和调用actor,并等待一些传入的数据,而是异步调用。 如何在没有例如关闭调用对象(在创建ActorRef时会传递回调,但这会捕获调用者)?

1 个答案:

答案 0 :(得分:0)

假设你有一个功能接口handleMessage - 即只接受不可变数据的方法handleMessage - 你可以简单地将它包装在Future中,在actor的上下文中运行:

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.
}