Kamila
03/21/2022, 7:13 AMCompletableFuture
of different entities, for example:
getFoo: CompletableFuture<List<FooDto>>
getBar: CompletableFuture<List<BarDto>>
getWhatever: CompletableFuture<List<WhateverDto>>
Would it be possible to use coroutines to trigger each of the call in parallel, and combine final object to be:
Object {
foo: List<FooDto>
bar: List<BarDto>
whatever: List<WhateverDto>
}
It is not so easy and obvious to solve with `CompletableFuture`s in Java, maybe it would be easier with coroutines
? 🤔 The point is I need to fetch multiple different entities before can calculate the final object. I can easily fetch them in sequence, but they are not dependant on each other, so should really be fetched in parallelritesh
03/21/2022, 7:26 AMWould it be possible to use coroutines to trigger each of the call in parallel, and combine final object to be:yes You can use
async
await
in co-routines (similar to get
) and in the end you can combine the results.Kamila
03/21/2022, 7:36 AMgetFoo().get()
getBar().get()
getWhatever.get()
In Java, but this is blocking call. Solution you mention means that all calls will be triggered and the process will wait for each of them to finish, meaning will take as long as the longest running task?uli
03/21/2022, 11:02 AMawait
is a suspend function
val fooFuture = getFoo()
val barFuture = getBar()
val whateverFuture = getWhatever()
Object {
foo = fooFuture.await()
bar = barFuture.await()
whatever = whateverFuture.await()
}
raulraja
03/21/2022, 2:32 PMawaitAll
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/await-all.html
We have also an encapsulation for this pattern in Arrow that looks like this https://github.com/arrow-kt/arrow/blob/a582273dacbbd8ae52b1acb52253b025720f5877/ar[…]-coroutines/src/commonMain/kotlin/arrow/fx/coroutines/ParZip.ktKamila
03/21/2022, 2:35 PMraulraja
03/21/2022, 2:36 PMawaitAll
on it’s own does not support multiple typed arguments and if your futures or deferred values are of different type. This is why we have parZip
otherwise awaitAll
would have worked. In general Kotlin does not let you abstract over arg arity, but in this operation there are multiple concerns such as cancellation and others that otherwise you need to handle manuallyDALDEI
06/05/2022, 10:10 AM