2017-07-11 37 views
1

正如akka文档所解释的那样,您应该可以通过这种方式在[[scala.concurrent.Future]]上获得pipeTo方法:无法在[[scala.concurrent.Future]]上获得`pipeTo`方法

import akka.pattern.pipe 
val future = ... 
future pipeTo sender() 

不幸的是,我不能这样做,我收到错误“无法解析符号pipeTo”在我的IDE中。

作为一种解决办法,我只好用语法这样

pipe(future) pipeTo sender() 

但它仍然打扰我不知道为什么(我很牛逼斯卡拉BTW)。非常感谢您帮助理解这个难题。

斯卡拉2.12.2 阿卡2.5.3

+2

你有一个隐式执行上下文的范围? –

回答

7

你需要有范围的implicit ExecutionContext,这里有一个例子:

import akka.actor.{Actor, ActorSystem, Props} 
import akka.pattern.pipe 

import scala.concurrent.Future 

// Get the implicit ExecutionContext from this import 
import scala.concurrent.ExecutionContext.Implicits.global 

object Hello extends App { 

    // Creating a simple actor 
    class MyActor extends Actor { 
    override def receive: Receive = { 
     case x => println(s"Received message: ${x.toString}") 
    } 
    } 

    // Create actor system 
    val system = ActorSystem("example") 
    val ref = system.actorOf(Props[MyActor], "actor") 

    // Create the future to pipe 
    val future: Future[Int] = Future(100) 

    // Test 
    future pipeTo ref 
} 

控制台:

sbt run 
[info] <stuff here> 
[info] Running example.Hello 
Received message: 100 

你必须这样做的原因是因为pipeTo是一个实例功能n在PipeableFuture,您的常规Future必须“增强”为PipeableFuture。下面是PipeableFuture构造,注意implicit executionContext: ExecutionContext参数:

final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) 

的满级是在这里,在这里你可以看到pipeTo功能:

final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) { 
    def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = { 
    future andThen { 
     case Success(r) ⇒ recipient ! r 
     case Failure(f) ⇒ recipient ! Status.Failure(f) 
    } 
    } 
    def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = { 
    future andThen { 
     case Success(r) ⇒ recipient ! r 
     case Failure(f) ⇒ recipient ! Status.Failure(f) 
    } 
    } 
    def to(recipient: ActorRef): PipeableFuture[T] = to(recipient, Actor.noSender) 
    def to(recipient: ActorRef, sender: ActorRef): PipeableFuture[T] = { 
    pipeTo(recipient)(sender) 
    this 
    } 
    def to(recipient: ActorSelection): PipeableFuture[T] = to(recipient, Actor.noSender) 
    def to(recipient: ActorSelection, sender: ActorRef): PipeableFuture[T] = { 
    pipeToSelection(recipient)(sender) 
    this 
    } 
} 

由于pipe(future)是不是在未来的实例函数,它在你的例子中起作用。