I would like to send network requests in queue. Wh...
# coroutines
k
I would like to send network requests in queue. What would be a best way to achieve this with coroutines? Shall I set limit dispather to a single thread?
e.g.
limitedParallelism(1)
s
If you want to make the requests one at a time, just send your requests to a Channel, and launch a single coroutine to read from the channel and execute the requests 👍
(Basically an actor pattern, though the dedicated
actor
builder in the stdlib is still marked as obsolete with no replacement 😞)
No need to limit the dispatcher in that scenario, since coroutines are sequential by default
g
@K Merle If your use case is network, can you do this on level of the client? HTTP clients for example usually have better ways to control concurrency (such as limit amount of connectios per domain)
k
@gildor I might wanna avoid setting this up on the client as this request requirement is not on the scope of the whole application, but rather single feature that is event-based. @Sam Gonna try that and see how it works.
g
If you just need a sequential execution, I prefer flow + map on each item
it allows explicitly execute some task sequentially
k
I'll look into it @gildor tnx
g
Using actor is also an option, but I think it’s a more appropriate pattern when you want dynamic parallelism Also keep in mind that thing like limitedParallelism limits only threads, it doesn’t limit parallel coroutine execution, so if you network request is asyncronous (and uses suspend functions) it will not limit it execution
k
Ah, thanks for the limitedParallelism explanation.