你需要有範圍的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)
是不是在未來的實例函數,它在你的例子中起作用。
你有一個隱式執行上下文的範圍? –