Skip to content

Instantly share code, notes, and snippets.

@k0pernikus
Created April 23, 2018 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k0pernikus/6bf263025c32a40adf959bb7b1d163c9 to your computer and use it in GitHub Desktop.
Save k0pernikus/6bf263025c32a40adf959bb7b1d163c9 to your computer and use it in GitHub Desktop.
LazyFuture for scala, prototype, wip, based on stackoverflow answer
package com.dreamlines.commons
import scala.concurrent.{ExecutionContext, Future}
/**
* This LazyFuture helps working with futures with concurrency
*
* @param f
* @tparam A
*/
case class LazyFuture[A](f: Unit => Future[A]) {
def apply(): Future[A] = f()
}
object LazyFuture {
var counter = 0
def apply[A](f: => A)(implicit ec: ExecutionContext): LazyFuture[A] = LazyFuture(_ => Future(f))
def apply[A](f: => Future[A]): LazyFuture[A] = LazyFuture(_ => f)
def executeBatch[A](list: List[LazyFuture[A]])(concurFactor: Int)
(implicit ec: ExecutionContext): Future[List[A]] =
list.grouped(concurFactor).foldLeft(
Future.successful(List.empty[A])
) { (r, c) =>
counter += 1
println(s"EXECTUTING: $counter")
val batch = Future.sequence(c.map(_ ()))
r.flatMap(rs => r.map(values => rs ++ values))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment