使用scalaz任务,我用 scalaz.Nondeterminism.both
做到这一点:
Nondeterminism[Task]
.both(
Task.now("Hello"),
Task.now("world")
)
或使用Nondeterminism[Task].gatherUnordered()
。
如何使用FS2 0.9.x版本任务做同样的事情?
我假设您在FS2版本上0.9.x。要并行执行多个任务,您只需调用Task.start
即可。这是文档的示例:
for {
f <- Task.start { expensiveTask1 }
// at this point, `expensive1` is evaluating in background
g <- Task.start { expensiveTask2 }
// now both `expensiveTask2` and `expensiveTask1` are running
result1 <- f
// we have forced `f`, so now only `expensiveTask2` may be running
result2 <- g
// we have forced `g`, so now nothing is running and we have both results
} yield (result1 + result2)
因此,在您的情况下,它看起来像这样:
for {
ta <- Task.start(Task.now("Hello"))
tb <- Task.start(Task.now("World"))
a <- ta
b <- tb
} yield (a, b)
请注意,将来有可能使用少于样板进行这样的事情。有一个PR添加Parallel
类型类,这将使我们能够写下这样的内容:
(taskA, taskB).parMapN((a, b) => ...)