Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created May 7, 2020 14:38
Show Gist options
  • Save fancellu/46cfbcdc381717d9d58bb6820c91e570 to your computer and use it in GitHub Desktop.
Save fancellu/46cfbcdc381717d9d58bb6820c91e570 to your computer and use it in GitHub Desktop.
Scala Future[Option[T]] example. Returns first successful future with Something in the Option of T
// Just a little example, but frankly, avoid Futures, they are eager and do not compose well
import scala.concurrent.Await
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
object FutOrElse extends App{
def getSource1(s: String): Future[Option[String]]=
Future {
println(s"Source1 running $s")
Some(s"from source1 $s")
}
def getSource2(s: String): Future[Option[String]]=
Future {
println(s"Source2 running $s")
Some(s"from source2 $s")
}
val failingSource=Future.successful(None)
// returns first successful future with Something in the Option of T
def futOrElse[T](fot1: =>Future[Option[T]], fot2: =>Future[Option[T]]): Future[Option[T]] ={
val f1=fot1
for {
option <- f1
res <- if (option.isDefined) f1 else fot2
} yield res
}
println("run1")
val pp1=futOrElse(getSource1("1"), getSource2("1"))
val out1=Await.result(pp1,3.seconds)
println(out1)
println("run2")
val pp2=futOrElse(failingSource, getSource2("2"))
val out2=Await.result(pp2,3.seconds)
println(out2)
println("run3")
val pp3=futOrElse(failingSource, failingSource)
val out3=Await.result(pp3,3.seconds)
println(out3)
}
run1
Source1 running 1
Some(from source1 1)
run2
Source2 running 2
Some(from source2 2)
run3
None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment