【问题标题】:How to simplify future result handling in Akka/Futures?如何简化 Akka/Futures 中的未来结果处理?
【发布时间】:2016-11-24 05:27:03
【问题描述】:

我想简化我的for comprehension 代码,使其尽可能简单。

这里是代码

case object Message

class SimpleActor extends Actor {
  def receive = {
    case Message => sender ! Future { "Hello" }
  }
}

object SimpleActor extends App {

  val test = ActorSystem("Test")
  val sa = test.actorOf(Props[SimpleActor])

  implicit val timeout = Timeout(2.seconds)

  val fRes = for {
    f <- (sa ? Message).asInstanceOf[Future[Future[String]]]
    r <- f
  } yield r

  println {
    Await.result(fRes, 5.seconds)
  }

}

有没有可能去掉这部分

.asInstanceOf[Future[Future[String]]]

?

【问题讨论】:

    标签: scala akka future


    【解决方案1】:

    查看pipeTo 函数,它是关于在Actor 之间传递Future。请参阅here 询问模式。

    myFuture pipeTo sender
    

    在您的情况下,您询问的返回类型将是 Future[String],正如您在下面的评论中询问的那样,您需要 mapTo[String] 才能实际获得结果类型为 String。因此,您的 for-comp 可能会被丢弃并直接调用:

     val fRes = (sa ? Message).mapTo[String]
    

    【讨论】:

    • 你的意思是我需要将接收函数更改为def receive = { case Message =&gt; Future("Hello").pipeTo(sender) } 并将结果映射到像这样for { f &lt;- (sa ? Message).mapTo[String] } yield f 的for-comp,对吗?
    • @Finkelson 是的,基本上。 pipeTo 使消息返回“扁平化”,这样您只会得到 Future
    • 嗯,这很有趣。谢谢。
    猜你喜欢
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    相关资源
    最近更新 更多