2014-05-12 47 views
2

我有下面的代碼並行期貨:如何動態生成與收益

val f1 = Future(genA1) 
    val f2 = Future(genA2) 
    val f3 = Future(genA3) 
    val f4 = Future(genA4) 

val results: Future[Seq[A]] = for { 
    a1 <- f1 
    a2 <- f2 
    a3 <- f3 
    a4 <- f4 
} yield Seq(a, b, c, d) 

現在我有一個要求,有選擇地排除A2,如何修改密碼? (有地圖或flatMap也可以)

此外,比如說如果我有M個將來可能需要像上面那樣聚合,並且N的M可以被選擇性地排除某些標誌(biz邏輯),我該如何處理它?

在此先感謝!

萊昂

+0

你的問題很難理解。 「可選」輸出b意味着什麼? if(outputB){... Seq(a,b,c,d)} else {Seq(a,c,d)}? – maasg

+0

對不起。我其實是指「退出」:)我改變了這個問題。 – anuni

回答

2

在問題1,我知道你是想排除從給定的一些邏輯和問題2,你想從總共M的剿N個條目的序列中的一個條目(例如B),並有未來根據這些結果計算。我們可以概括這兩種情況下是這樣的:

// Using a map as simple example, but 'generators' could be a function that creates the required computation 
val generators = Map('a' -> genA1, 'b' -> genA1, 'c' -> genA3, 'd' -> genA4) 
... 
// shouldAccept(k) => Business logic to decide which computations should be executed. 
val selectedGenerators = generators.filter{case (k,v) => shouldAccept(k)} 
// Create Seq[Future] from the selected computations 
val futures = selectedGenerators.map{case (k,v) => Future(v)} 
// Create Future[Seq[_]] to have the result of computing all entries. 
val result = Future.sequence(futures) 

在一般情況下,我認爲你正在尋找的是Future.sequence,這需要一個Seq[Future[_]]併產生Future[Seq[_]],這基本上是你在做什麼「手動」與理解。

+0

非常感謝!我會試一試。 – anuni