Created
          August 8, 2013 07:06 
        
      - 
      
- 
        Save aaronlifton3/6182235 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package com.snowdale.play.extensions | |
| import com.twitter.util.{ Future, Return, Throw , Duration} | |
| import play.api.libs.concurrent._ | |
| import java.util.concurrent.TimeUnit | |
| object Finagle { | |
| implicit def futureTransform[A](future: Future[A]) = new FinagleFuture(future) | |
| } | |
| class FinagleFuture[A](future: Future[A]) { | |
| /** | |
| * Transform this Finagle future to a Play Promise. | |
| */ | |
| def asPromise: Promise[A] = new FinaglePromise(future) | |
| } | |
| class FinaglePromise[A](future: Future[A]) extends Promise[A] { | |
| def onRedeem(k: A => Unit): Unit = | |
| future.respond { | |
| case Return(value) => k(value) | |
| case Throw(t) => Thrown(t) | |
| } | |
| def extend[B](k: Function1[Promise[A], B]): Promise[B] = { | |
| val p = Promise[B]() | |
| future.onSuccess { case a => p.redeem(k(this)) } | |
| future.onFailure { case e => p.redeem(k(this)) } | |
| p | |
| } | |
| def await(timeout: Long, unit: TimeUnit = TimeUnit.MILLISECONDS): NotWaiting[A] = { | |
| try { | |
| Redeemed(future(Duration.fromTimeUnit(timeout, unit))) | |
| } catch { | |
| case e => Thrown(e) | |
| } | |
| } | |
| def filter(p: A => Boolean): Promise[A] = { | |
| new FinaglePromise[A](future.filter(p)) | |
| } | |
| def map[B](f: A => B): Promise[B] = new FinaglePromise[B](future.map(f)) | |
| def flatMap[B](f: A => Promise[B]): Promise[B] = { | |
| val result = Promise[B]() | |
| future.onSuccess { | |
| case a => f(a).extend1 { | |
| case Redeemed(a) => result.redeem(a) | |
| case Thrown(e) => result.throwing(e) | |
| } | |
| } | |
| future.onFailure { case e => result.throwing(e) } | |
| result | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment