在kotlin中是否有Future.sequence类似物?

Che*_*rry 1 scala future kotlin completable-future

在scala中,你可以将未来的集合"映射"到集合的未来:

val l: List[Future[String]]  = List(Future {"1"}, Future {"2"})
val x: Future[List[String]] = Future.sequence(l)
Run Code Online (Sandbox Code Playgroud)

如何用kotlin同样的事情?

vod*_*dan 5

假设您使用协同程序:

val l: List<Deferred<String>>  = (1..2).map {i -> async(Unconfined){ "$i" }}
val x: Deffered<List<String>> = async(Unconfined) { l.map {it.await()} }
Run Code Online (Sandbox Code Playgroud)

  • 如果由于Java互操作而必须使用`CompletebleFuture`,那么你可以使用几乎相同的代码将`List <CompletableFuture <String >>`转换为`CompletableFuture <List <String >>`,只需将`async` builder替换为`来自`kotlinx-coroutines-jdk8`的未来`建设者 (2认同)