2017-04-08 42 views
0

我想知道如何立即終止理解而不調用Future.failed併產生Try [Failure]結果。如何立即屈服?嘗試理解內部?

例子:

for { 
    resultOne <- Future { Successful("Data") } 
    resultTwo <- Future { 
     // Something went wrong here... 
     // Instead of calling Future.failed(); 
     // I want to terminate this for-comprehension and return a 
     // Failure() object and bypass the next line 
    } 
    resultThree <- Future { 
     // Something went wrong here... 
     // Instead of calling Future.failed(); 
     // I want to terminate this for-comprehension and return a 
     // Failure() object and bypass the next line 
    } 
    resultFour <- Future { 
     // ... Some database call which retuns a Try[] 
    } 
} yield resultFour 

又如

你在說我的例子不是並行運行是正確的。我想我沒有其他選擇,只能做到這一點?

for { 
    resultOne <- Future { Successful("Data") } 
    resultFour <- { 
     // ... Some async function which returns a Try 
     } 
     .flatMap { 
      case Success(resultTwo) => // ... Some async function which returns a Try 
      case Failure(ex) => Future.success(Failure(ex)) 
     } 
     .flatMap { 
      case Success(resultTwo) => // ... Some database call which retuns a Try[] 
      case Failure(ex) => Future.success(Failure(ex)) 
     } 
    } 
} yield resultFour 

回答

0

你有什麼有這種快速失敗的行爲,但不是並行運行!您需要在理解之外創建期貨才能並行運行它們。

幕後沒有理解,它是map/flatMap上的語法糖。所以這不是一個可以取消整體的「事情」。

我假設你想要的是在其中一個失敗時停止其他期貨(例如,爲了節省資源或任何失敗後立即返回)。斯卡拉的期貨不支持這一點。 Monix是一個提供支持這個用例的CanceleableFuture的scala庫。

+0

我想我沒有選擇。我已更新我的帖子並添加了另一個示例。 –