Skip to content

Instantly share code, notes, and snippets.

@gabfssilva
Created August 29, 2017 05:33
Show Gist options
  • Save gabfssilva/e211de31095d8595d190fb6efcaaecfd to your computer and use it in GitHub Desktop.
Save gabfssilva/e211de31095d8595d190fb6efcaaecfd to your computer and use it in GitHub Desktop.
pipeline
package me.lavando.user.api.features
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scala.util.Failure
/**
* @author Gabriel Francisco <[email protected]>
*/
object Example extends App{
implicit class NiceArrow[A, B](func: (Future[A] => Future[B])) {
def ~>[C](f: Future[B] => Future[C]): (Future[A]) => Future[C] = func andThen f
def run(eventualA: Future[A]): Future[B] = func(eventualA)
}
implicit class FutureHandler[A](result: Future[A]) {
def handling[E <: Exception](t: E => Unit): Future[A] = {
result.onComplete {
case Failure(e: E) => t(e)
case _ =>
}
result
}
}
def mapToInt: Future[String] => Future[Int] = str => str map { s => s.toInt }
def sumTwo: Future[Int] => Future[Int] = int => int map { i => i + 2 }
def multiplyThree: Future[Int] => Future[Int] = int => int map { i => i * 3 }
// def multiplyThree: Future[Int] => Future[Int] = int => int map { i => i / 0 }
def showResultAsMessage: Future[Int] => Future[String] = int => int map { i => s"the result is equal to $i" }
val pipeline = mapToInt ~> sumTwo ~> multiplyThree ~> showResultAsMessage
val result =
pipeline
.run(Future { "2" })
.handling { (e: ArithmeticException) => println("ups...") }
.handling { (e: IllegalArgumentException) => println("ups...") }
println(Await.result(result, 2 seconds))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment