No Name
No Name

Reputation: 793

How to Wait response from Server in forEach with Coroutines

I recently started working with coroutines.

The task is that I need to check the priority parameter from the List and make a request to the server, if the response from the server is OK, then stop the loop.

var minPriority = 0
list.forEach { model -> 
   if (model.priority > minPriority) {
       makeRequest(model.value)
       minPriority = model.priority
   }
}

private fun makeRequest(value: String) {
    scope.launch() {
        val response = restApi.makeRequest()
        if response.equals("OK") {
            **stop list foreach()**
        }
    }
}

In RxJava, this was done using the retryWhen() operator, tell me how to implement this in Coroutines?

Upvotes: 0

Views: 763

Answers (1)

broot
broot

Reputation: 28452

I suggest making your whole code suspendable, not only the body of makeRequest() function. This way you can run the whole operation in the background, but internally it will be sequential which is easier to code and maintain.

It could be something like this:

scope.launch() {
    var minPriority = 0
    list.forEach { model ->
        if (model.priority > minPriority) {
            val response = restApi.makeRequest()
            if response.equals("OK") {
                return@forEach
            }
            minPriority = model.priority
        }
    }
}

Of if you need to keep your makeRequest() function separate:

fun myFunction() {
    scope.launch() {
        var minPriority = 0
        list.forEach { model ->
            if (model.priority > minPriority) {
                if (makeRequest(model.value)) {
                    return@forEach
                }
                minPriority = model.priority
            }
        }
    }
}

private suspend fun makeRequest(value: String): Boolean {
    val response = restApi.makeRequest()
    return response.equals("OK")
}

Upvotes: 1

Related Questions