Created
October 4, 2011 22:19
-
-
Save Sciss/1263011 to your computer and use it in GitHub Desktop.
Thin wrapping around `scala.actors.Future` to allow for a `set` method to resolve the `Future`.
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
import collection.immutable.{IndexedSeq => IIdxSeq} | |
import actors.{Futures, Actor, Future} | |
trait FutureResult[ A ] { | |
def isSet : Boolean | |
def apply() : A | |
def respond( fun: A => Unit ) : Unit | |
def map[ B ]( fun: A => B ) : FutureResult[ B ] | |
def flatMap[ B ]( fun: A => FutureResult[ B ]) : FutureResult[ B ] | |
def peer : Future[ A ] | |
} | |
object FutureResult { | |
trait Event[ A ] extends FutureResult[ A ] { | |
def set( result: A ) : Unit | |
} | |
def event[ A ]() : FutureResult.Event[ A ] = new FutureResult.Event[ A ] with Basic[ A ] { | |
final case class Set( value : A ) | |
case object Get | |
val act = Actor.actor { | |
import Actor._ | |
react { | |
case set @ Set( value ) => react { | |
case Get => reply( set ) | |
} | |
} | |
} | |
val peer = Futures.future { | |
import Actor._ | |
act ! Get | |
receive { | |
case Set( value ) => value | |
} | |
} | |
def set( value: A ) { act ! Set( value )} | |
} | |
def wrap[ A ]( fut: Future[ A ]) : FutureResult[ A ] = new FutureResult[ A ] with Basic[ A ] { | |
def peer = fut | |
} | |
private sealed trait Basic[ A ] { | |
me: FutureResult[ A ] => | |
def map[ B ]( fun: A => B ) : FutureResult[ B ] = wrap( Futures.future { | |
fun( me.peer.apply() ) | |
}) | |
def flatMap[ B ]( fun: A => FutureResult[ B ]) : FutureResult[ B ] = wrap( Futures.future { | |
fun( me.peer.apply() ).peer.apply() | |
}) | |
def isSet : Boolean = peer.isSet | |
def apply() : A = peer.apply() | |
def respond( fun: A => Unit ) { peer.respond( fun )} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment