Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two Scala Future[List]

Tags:

scala

future

I need to combine two Future[List] into one and I came up with the following solution:

    def mergeFutureLists[X]( fl1: Future[List[X]], fl2: Future[List[X]] ): Future[List[X]] =
    {
        val lf = List( fl1, fl2 )
        val fll = Future.sequence( lf )
        return fll.map{ x => x.flatMap{ el => el } }
    }

It does what I want but is it the right way to proceed?

like image 379
david Avatar asked Dec 18 '15 23:12

david


1 Answers

You can wait for the results then combine those into a list:

def mergeFutureLists[X]( fl1: Future[List[X]], fl2: Future[List[X]] ) = {
  for{
    f1Res <- fl1
    f2Res <- fl2
  } yield (f1Res ::: f2Res)
}
like image 138
znurgl Avatar answered Oct 09 '22 10:10

znurgl