Created
April 23, 2018 13:39
-
-
Save k0pernikus/6bf263025c32a40adf959bb7b1d163c9 to your computer and use it in GitHub Desktop.
LazyFuture for scala, prototype, wip, based on stackoverflow answer
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 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