Add Future.receive(pf: PartialFunction[Any,Unit]), closes #636

This commit is contained in:
Derek Williams 2011-02-13 21:11:37 -07:00
parent 7437209ff4
commit e7ad2a9d5d
2 changed files with 19 additions and 0 deletions

View file

@ -169,6 +169,17 @@ sealed trait Future[T] {
def onComplete(func: Future[T] => Unit): Future[T]
/**
* When the future is compeleted, apply the result to the provided PartialFunction if a match is found
*/
final def receive(pf: PartialFunction[Any, Unit]): Future[T] = onComplete { f =>
val optr = f.result
if (optr.isDefined) {
val r = optr.get
if (pf.isDefinedAt(r)) pf(r)
}
}
/**
* Returns the current result, throws the exception is one has been raised, else returns None
*/

View file

@ -204,4 +204,12 @@ class FutureSpec extends JUnitSuite {
assert(undone.size === 5)
assert(errors.size === 0)
}
@Test def receiveShouldExecuteOnComplete {
val latch = new StandardLatch
val actor = actorOf[TestActor].start
actor !!! "Hello" receive { case "World" => latch.open }
assert(latch.tryAwait(5, TimeUnit.SECONDS))
actor.stop
}
}