如何使用Coroutines在forEach中等待服务器的响应



我最近开始使用协同程序。

任务是,我需要检查List中的priority参数,并向服务器发送request,如果服务器的响应正常,则停止循环。

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()**
}
}
}

在RxJava中,这是使用retryWhen()运算符完成的,请告诉我如何在Coroutines中实现这一点?

我建议将整个代码挂起,而不仅仅是makeRequest()函数的主体。通过这种方式,您可以在后台运行整个操作,但在内部它将是顺序的,这更容易编码和维护。

可能是这样的:

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
}
}
}

如果您需要将makeRequest()功能分开:

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")
}

最新更新