Last active
September 18, 2015 16:00
-
-
Save alexandru/1f312da99708450577a0 to your computer and use it in GitHub Desktop.
This file contains 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 different.future | |
import concurrent.ExecutionContext | |
import scala.util.Try | |
/** | |
* Just a tuple formed from a callback and an ExecutionContext. | |
* | |
* @param callback is the function called whenever we've got the value to signal | |
* @param context is the thread-pool under which our tasks are running | |
*/ | |
case class OnComplete[-T](callback: Try[T] => Unit, context: ExecutionContext) | |
/** | |
* An alternative to the Future as designed in Scala's standard library. | |
*/ | |
trait Future[+T] { self => | |
/** Characteristic abstract function */ | |
def run(onComplete: OnComplete[T]): Unit | |
/** This would be the equivalent of Scala's Future.onComplete */ | |
def run(cb: Try[T] => Unit)(implicit ec: ExecutionContext): Unit = | |
run(OnComplete(cb, ec)) | |
/** Look mom, no implicit ExecutionContext */ | |
def map[U](f: T => U): Future[U] = | |
Future.create[U] { u => | |
implicit val ec = u.context | |
self.run(tryT => u.callback(tryT.map(f))) | |
} | |
/** Look mom, no implicit ExecutionContext */ | |
def flatMap[U](f: T => Future[U]): Future[U] = | |
Future.create[U] { u => | |
implicit val ec = u.context | |
self.run(tryT => tryT.flatMap(t => Try(f(t)).map(_.run(u)))) | |
} | |
} | |
object Future { | |
def create[T](f: OnComplete[T] => Unit): Future[T] = | |
new Future[T] { | |
def run(onComplete: OnComplete[T]): Unit = | |
f(onComplete) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment