我有一个使用 for-comprehension 运行数据库查询的代码:
val totalFeeNoticeAmountFromDB = Future(/..Doing db job../)(executionContext)
val listOfRestrictedFundFromDB = Future(/..Doing db job../)(executionContext)
val res = for {
totalFeeNoticeAmount <- totalFeeNoticeAmountFromDB
listOfRestrictedFund <- listOfRestrictedFundFromDB
} yield (totalFeeNoticeAmount, listOfRestrictedFund)
Run Code Online (Sandbox Code Playgroud)
我们知道运行 for-comprehension 我们需要传递隐式执行上下文。但在这种情况下,我想手动传递执行上下文。
方法是什么?
编辑:
val res = for {
totalFeeNoticeAmount <-(?:ExecutionContext) totalFeeNoticeAmountFromDB
listOfRestrictedFund <-(?:ExecutionContext) listOfRestrictedFundFromDB
} yield (totalFeeNoticeAmount, listOfRestrictedFund)
Run Code Online (Sandbox Code Playgroud)
totalFeeNoticeAmountFromDB并且listOfRestrictedFundFromDB都是 Future 类型已经启动。
有什么办法可以通过这里
<-(?:ExecutionContext)吗?
也许可以考虑在 Scala 2.13.3 中获得实验性编译器支持的scala-async,其中以下 for-comprehension -Xasync
for {
a <- Future(41)
b <- Future(1)
} yield {
a + b
}
Run Code Online (Sandbox Code Playgroud)
可以改写为
async {
val a = async(41)(ec)
val b = async(1)(ec)
await(a) + await(b)
}(ec)
Run Code Online (Sandbox Code Playgroud)
我们可以ec显式地传入执行上下文,而无需求助于 flatMap/map。
另一个 hacky 选项可能是 Better -monadic-for,它支持在 for-comprehensions 中定义隐式
val ec: ExecutionContext = ???
(for {
implicit0(ec: ExecutionContext) <- Future.successful(ec)
a <- Future(41)(ec)
b <- Future(1)(ec)
} yield {
a + b
})(ec)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
334 次 |
| 最近记录: |