Salil Luley
Salil Luley

Reputation: 1421

How to use a coroutine inside forEach loop in Kotlin?

I want have an array of objects which I want to loop over and send every object using a post request and CoroutineScope to server.

Upvotes: 0

Views: 3940

Answers (1)

Evgeny  Bovykin
Evgeny Bovykin

Reputation: 3079

You can use the following pattern:

  1. Map your list/array to async jobs
  2. Map list of async jobs to their result

In code, it'd look like this

myData.map { data ->
    async {
        callToServer(data)
    }
}.map {
    it.await()
}

This would run each callToServer in separate job concurrently.

Upvotes: 3

Related Questions