https://kotlinlang.org logo
#coroutines
Title
# coroutines
e

Esa

02/27/2020, 8:58 AM
This will create 1 job for every element of the list, regardless of how large the list is, which will attempt to then run in parallel. May or may not be the behaviour you want.
t

Timur Atakishiev

02/27/2020, 8:59 AM
Thank you for an answer, I know that the list is going to to be 10 elements always. I want to execute sumeFunction on every element of the list, is it the ride code?
e

Esa

02/27/2020, 9:01 AM
Yes, as long as you expect nothing in return and don’t mind all 10 starting at once and running in parallel, this should do the trick. Although, I don’t get the while(true) and delay parts, why do you want those?
t

Timur Atakishiev

02/27/2020, 9:04 AM
There is a logic behind someFunction, it is checks the database and if there is required record it starts to work with it. My question is , does it matter what someFunction has inside? Or it will be inevitable running in 10 coroutines?
e

Esa

02/27/2020, 9:08 AM
launch
simply creates a`Job` element that is then run at once. As you iterate on a list with
forEach
, every element of that list will trigger a new job through launch. So you will create
n
amount of jobs from the coroutineScope provided from
runBlocking
. This is my understanding at least.
k

Kroppeb

02/27/2020, 6:17 PM
This is incorrect, the posted code will run concurrently, not parallel. This code will run 11 coroutines. The initial one and one for each element. However, it will all be run on 1 thread, the main thread. Note that the
delay(1000)
won't wait for all those coroutines to finish.
e

Esa

02/28/2020, 11:07 AM
Thank you for the correction.
3 Views