class: center, middle # Tricks with Futures by Stephen Nancekivell --- # Agenda 1. What are Futures 2. Tricks! --- # What are Futures --- # What are Futures Data Type, container for a value, ```scala class Future[T] { ... } ``` ```scala val one = Future { 1 } val two = Future { Thread.sleep(1000) 2 } ``` --- # What are Futures Data Type, container for a value, ```scala class Future[T] { def map[A](fn: T => A): Future[A] } ``` --- # What are Futures Data Type, container for a value, ```scala class Future[T] { def map[A](fn: T => A): Future[A] } ``` ```scala val one = Future { 1 } val two = one.map { oneValue => oneValue + 1 } // Future(2) ``` --- # What are Futures Data Type, container for a value, ```scala class Future[T] { def map[A](fn: T => A): Future[A] def flatMap[A](fn: T => Future[A]): Future[A] } ``` --- # What are Futures ```scala class Future[T] { def map[A](fn: T => A): Future[A] def flatMap[A](fn: T => Future[A]): Future[A] } ``` ```scala val futureId: Future[Int] = ??? def find(id: Int): Future[String] = ??? val result: Future[String] = futureId.flatMap { id => find(id) } ``` --- # Tricks --- # Tricks I have lots of futures and I want all of their values to work with at once. --- # live coding (☞゚∀゚)☞ --- ```scala def lotsOfFutures: Seq[Future[Int]] = ??? def wanted : Future[Seq[Int]] = ??? def sequence(xs: Seq[Future[Int]]): Future[Seq[Int]] = { xs.foldLeft(Future(Seq[Int]())){ case (acc, item) => acc.flatMap { accValue => item.map { itemValue => accValue :+ itemValue } } } } ``` --- # Tricks I am making too many futures at once, my database cant keep up! --- # live coding (☞゚∀゚)☞ --- ```scala def inputList: Seq[Int] = ??? def find(i: Int): Future[String] = ??? def wanted: Future[Seq[Int]] = ??? def traverse(xs: Seq[Int])(fn: Int => Future[String]): Future[Seq[String]] = { xs.foldLeft(Future(Seq[String]())) { (acc, item) => acc.flatMap { accValue => fn(item).map { itemValue => accValue :+ itemValue } } } } ``` --- # Monads Monads Monads --- # Monads Monads Monads ![Monad](/assets{{ page.id }}/buritto.jpeg) --- # Monads ```scala class Future[T] { def map[A](fn: T => A): Future[A] def flatMap[A](fn: T => Future[A]): Future[A] } ``` --- # Monads ```scala class Future[T] { def map[A](fn: T => A): Future[A] def flatMap[A](fn: T => Future[A]): Future[A] } ``` ```scala trait Monad[T] { def map[A](fn: T => A): Monad[A] def flatMap[A](fn: T => Monad[A]): Monad[A] } ``` --- # Thank You ![Future](/assets{{ page.id }}/delorean.jpg)