Merging Two Scala Future [List]

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 } }
    }

He does what I want, but is this the right way to continue?

+4
source share
5 answers

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

def mergeFutureLists[X]( fl1: Future[List[X]], fl2: Future[List[X]] ) = {
  for{
    f1Res <- fl1
    f2Res <- fl2
  } yield (f1Res ::: f2Res)
}
+5
source

You can also use Future.reduce:

def mergeFutureLists[X]( fl1: Future[List[X]], fl2: Future[List[X]]) = {
  Future.reduce(List(fl1, fl2))(_ ++ _)
}

Or for an arbitrary number of future lists:

def mergeFutureLists[X](fl: Future[List[X]]*): Future[List[X]] = {
  Future.reduce(fl)(_ ++ _)
}
+3
source

, "", , . :

def mergeFutureLists[X](fl1: Future[List[X]], fl2: Future[List[X]]): Future[List[X]]

:

def mergeFutureLists[X](fl: Future[List[X]]*): Future[List[X]]

fold :

  def mergeFutureLists[X](fl: Future[List[X]]*): Future[List[X]] = 
        Future.fold(fl)(List.empty[X])(_ ++ _)

, @Kolmar

++ (list concatenate) Future. @znurgl , , : :::. , , : for-comprehension, zip fold.

fold (catamorphism), , .

+1

List, , zip:

def mergeFutureLists[X](fl1: Future[List[X]], 
                        fl2: Future[List[X]]): Future[List[X]] = 
  fl1 zip fl2 map Function.tupled(_ ++ _)
+1

, Future.collect:

collect takes a set of futures of the same type and gives the future a sequence of values ​​of that type. This future is complete when all underlying futures are complete or when one of them has failed. The order of the returned sequences corresponds to the order of the sequence passed.

val combinedFuture: Future[Seq[List[X]]] =  Future.collect(Seq(fl1, fl1))

Then you can simply match the two lists after the future returns.

0
source

Source: https://habr.com/ru/post/1620827/


All Articles