2017-07-11 36 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)是不是在未來的實例函數,它在你的例子中起作用。