2017-07-31 46 views
1

我要在理解中斯卡拉混合列表和期貨的理解中

val list: List[Int] = List(1,2,3) 
def f1(i: Int): Future[Boolean] = ??? 
def f2(i: Int): Future[List[Int]] = ??? 

看着this answer 如果我包裹清單,未來ANS CONVER的F返回類型列出這工作得很好混合列表和期貨

import scalaz._ 
import ListT._ 
val x: Future[List[Boolean]] = (for { 
    i <- listT(Future{ls}) 
    c <- listT(f2(i)) 
    b <- listT(f1(c).map(List(_))) 
} yield b).run 

,我尋找的輸出應爲Future[List[Boolean]]

但它似乎低效的所有THI用Future包裝列表並將布爾值轉換爲列表。和我不得不使用另一個庫(斯卡拉)

任何建議,以簡化它?

回答

2

使用Future.sequence運營商期貨序列映射到序列的未來:

val x: Future[List[Boolean]] = Future.sequence(list.map(f2)) // Change List[Future[List[Int]]] to Future[List[List[Int]]] 
.map(_.flatten) // to Future[List[Int]] 
.flatMap(list => Future.sequence(list.map(f1))) // map the new list when available to List[Future[Boolean]], and Future.sequence that to Future[List[Boolean]] !