Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[writing-async-app-in-scala-part-2] executeLazily implementation
def executeLazily[Argument, Return](argument: Argument,
list: List[Argument => Future[Option[Return]]])
(implicit ec: ExecutionContext): Future[Option[Return]] = {
val promise = Promise[Option[Return]]()
val iterator = list.iterator
def completeWith(t: Try[Option[Return]]): Unit = t match {
case Success(value) =>
if (value.isDefined || !iterator.hasNext)
promise.success(value)
else
// ↓ DANGER IS HERE
iterator.next().apply(argument).onComplete(completeWith)
case Failure(exception) =>
promise.failure(exception)
}
completeWith(Success(None))
promise.future
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment