add pimp for Future.pipeTo(Channel), closes #1235

cherry-picked from release-1.3

The ticket contains more methods around this issue, both on Actor and
Future itself, but I think it is better to provide the basic primitive
in a way which does not further couple Future and Actor. Will need to be
revisited for 2.0.
This commit is contained in:
Roland 2011-10-16 18:33:35 +02:00
parent 3e3f5320f6
commit c54e7b2a28
2 changed files with 45 additions and 0 deletions

View file

@ -0,0 +1,34 @@
/**
* Copyright (C) 2009-2011 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.dataflow
import akka.actor.{ Actor, Props }
import akka.dispatch.Future
import akka.actor.future2actor
import akka.util.duration._
import akka.testkit.AkkaSpec
class Future2ActorSpec extends AkkaSpec {
"The Future2Actor bridge" must {
"support convenient sending to multiple destinations" in {
Future(42) pipeTo testActor pipeTo testActor
expectMsgAllOf(1 second, 42, 42)
}
"support reply via channel" in {
val actor = app.actorOf(Props(new Actor {
def receive = {
case "do" Future(31) pipeTo context.channel
case "ex" Future(throw new AssertionError) pipeTo context.channel
}
}))
(actor ? "do").as[Int] must be(Some(31))
intercept[AssertionError] {
(actor ? "ex").get
}
}
}
}

View file

@ -22,4 +22,15 @@ package object actor {
n.substring(i + 1).replaceAll("\\$+", ".")
}
implicit def future2actor[T](f: akka.dispatch.Future[T]) = new {
def pipeTo(channel: Channel[T]): this.type = {
if (f.isCompleted) {
f.value.get.fold(channel.sendException(_), channel.tryTell(_))
} else {
f onComplete { _.value.get.fold(channel.sendException(_), channel.tryTell(_)) }
}
this
}
}
}