rrva
01/29/2019, 7:22 AMprivate fun <A, B> Iterable<A>.parallelMap(context: CoroutineContext, f: suspend (A) -> B): List<B> = runBlocking {
map { async(context) { f(it) } }.map { it.await() }
}
val listOfIds.parallelMap(fooApiPool) { fooApiClient.fetchStuff(it)}
(found at: https://jivimberg.io/blog/2018/05/04/parallel-map-in-kotlin/)
But what about orchestrating calls to several sources (clients calls could be made suspendable if this is important), where we for example have three source API:s which we would like to be called in parallel, and then the values are awaited and collected? (I'm trying to get rid of RxJava for some use-cases where I found it to be a burden to maintain/debug). What are good patterns here for expressing the execution flow?gildor
01/29/2019, 7:36 AMrrva
01/29/2019, 7:37 AMgildor
01/29/2019, 7:38 AMrrva
01/29/2019, 7:39 AMgildor
01/29/2019, 7:42 AMgildor
01/29/2019, 7:43 AMfooApiClient.fetchStuff
is blocking, you shouldn’t create special functions to run it, but instead, at least wrap it to coroutine, so it will be non-blocking at leastrrva
01/29/2019, 7:43 AMgildor
01/29/2019, 7:43 AMI meant parallelMap should go into the standard coroutine library
gildor
01/29/2019, 7:44 AMgildor
01/29/2019, 7:45 AMrunBlocking
or any blocking solutionsrrva
01/29/2019, 7:45 AMgildor
01/29/2019, 7:45 AMgildor
01/29/2019, 7:47 AMgildor
01/29/2019, 7:48 AMgildor
01/29/2019, 7:49 AMfooApiClient.fetchStuff
is blocking, but why it’s blocking? This example looks as some network request, which of course shouldn’t be blocking and much more optimal way would be to use non-blocking version of network requestrrva
01/29/2019, 7:57 AMawaitAll
?gildor
01/29/2019, 7:58 AMI would need all clients to be non-blocking and useIt’s not something what you must to do, but it’s definitely would be good in terms of performance and coroutines ideology?awaitAll
gildor
01/29/2019, 8:01 AMsuspend fun call(): withContext(IO) { blockingCall() }
, so it allows you to use them with non-blocking code, but this approacch is also not perfect, you don’t have proper cancellation support, but it’s already closer to usual coroutine usagegildor
01/29/2019, 8:01 AM