https://kotlinlang.org logo
Title
s

silas.schwarz

11/15/2018, 9:23 AM
hey just a quick question since i'm not to firm with coroutines yet. how would you tackle something that you want to do in parallel (network request) but need to assure that there are never more than 4 requests in parallel (threadpoolexecutor but in coroutines). i've seen that so can assign work to pools (CommonPool) etc but can you create your own pool and define it's parallelism ?! thx 😙
g

gildor

11/15/2018, 9:24 AM
Better to use worker pool pattern for that
using CommonPool, or any other custom dispatcher will not work for any async API that doesn’t block threads or has own thread pool (like every http client with async api)
There is an issue to provide built in implementation of working pool https://github.com/Kotlin/kotlinx.coroutines/issues/172
Also, see this talk by Roman, there is a part about limiting concurrency that explains this idea and pattern:

https://youtu.be/a3agLJQ6vt8?t=1112

But in some cases, like for example in case HTTP client, you have some APIs to limit concurrency on library level, some http client allow to do that, also providing more smart limiting, based on host, network state etc
but approach with working pool is universal solution ffor this
s

silas.schwarz

11/15/2018, 9:30 AM
thank you very much for all the input!
🙇‍♂️
g

gildor

11/15/2018, 9:32 AM
👍
s

silas.schwarz

11/15/2018, 9:33 AM
i used rxkotlin and okhttp which makes it easy to enforce only 4 in parallel but i was trying to build something in plain kotlin and coroutines as an alternative. thanks
g

gildor

11/15/2018, 9:33 AM
okhttp has built in mechanism to limit concurrency