与 pipeTo 等效的 Akka 类型是什么?

1fl*_*flx 6 scala akka akka-typed

我目前正在尝试将现有的无类型演员重写为有类型的演员。由于参与者正在使用 ScalikeJDBC 与 MySQL 数据库进行对话,并且由于我希望异步完成,因此我正在处理来自单独(非参与者)存储库类的 Futures。

使用无类型 Akka,在演员的接收方法中,我可以这样做:

import akka.pattern.pipe
val horseList : Future[Seq[Horse]] = horseRepository.listHorses(...)
horseList pipeTo sender()
Run Code Online (Sandbox Code Playgroud)

发送者 actor 最终会收到一个马匹列表。我无法弄清楚如何在行为中执行此操作,例如:

val behaviour : Behavior[ListHorses] = Behaviors.receive { 
    (ctx,msg) => msg match {
        case ListHorses(replyTo) => 
            val horseListF : Future[Seq[Horse]] = horseRepository.listHorses(...)
            // -> how do I make horseListF's content end up at replyTo? <-
            Behaviors.same
    }
}
Run Code Online (Sandbox Code Playgroud)

管道模式不起作用(因为它需要一个无类型的 ActorRef),到目前为止我还没有在akka-actor-typed(2.5.12) 依赖项中找到任何其他东西,我正在使用它来完成这项工作。

我该怎么做呢?

lex*_*x82 1

replyTo当 future 成功完成时,您可以简单地发送一条消息:

case ListHorses(replyTo) => 
    horseRepository.listHorses(...) foreach { horses => replyTo ! horses }
    Behaviors.same
Run Code Online (Sandbox Code Playgroud)

或者如果您也想处理错误:

case ListHorses(replyTo) =>
    horseRepository.listHorses(...) onComplete { 
        case Success(horses) => replyTo ! horses
        case Failure(e) => // error handling 
    }
    Behaviors.same
Run Code Online (Sandbox Code Playgroud)

为了使其工作,您需要一个ExecutionContext. 使用与演员相同的角色通常是有意义的,因此您必须首先将其提供给onComplete或:foreach

implicit val ec = ctx.executionContext
Run Code Online (Sandbox Code Playgroud)