Я медленно изучаю kotlin-coroutines
и хочу начать с простого случая, когда я перебираю список и каждый раз вызываю вызов API, жду ответа, делаю с ним и затем повторяю процесс каждую итерацию.
viewModelScope.launch {
list.forEach { item ->
Log.d("TESTING", "forEach iteration before calling test(): ${item.id}")
test()
Log.d("TESTING", "forEach iteration after calling test(): ${item.id}")
}
}
suspend fun test(item.id: String) = coroutineScope {
Log.d("TESTING", "suspend test before receiving response: ${item.id}")
val apiRepsonse = async {
repository.doingApiCall() {
Log.d("TESTING", "response: ${item.id}")
}
}.await()
Log.d("TESTING", "suspend test after receiving response: ${item.id}")
}
Итак, если мы представим, что list
содержит: { 10, 15, 25, 35 }
(идентификаторы)
Я бы хотел получить в logcat
следующее:
Log.d("TESTING", "forEach iteration before calling test(): 10")
Log.d("TESTING", "suspend test before receiving response: 10")
Log.d("TESTING", "response: 10")
Log.d("TESTING", "suspend test after receiving response: 10")
Log.d("TESTING", "forEach iteration after calling test(): 10")
___________________
Log.d("TESTING", "forEach iteration before calling test(): 15")
Log.d("TESTING", "suspend test before receiving response: 15")
Log.d("TESTING", "response: 15")
Log.d("TESTING", "suspend test after receiving response: 15")
Log.d("TESTING", "forEach iteration after calling test(): 15")
...
Но , прямо сейчас я получаю что-то вроде этого:
Log.d("TESTING", "forEach iteration before calling test(): 10")
Log.d("TESTING", "suspend test before receiving response: 10")
Log.d("TESTING", "suspend test after receiving response: 10")
Log.d("TESTING", "forEach iteration after calling test(): 10")
Log.d("TESTING", "forEach iteration before calling test(): 15")
Log.d("TESTING", "suspend test before receiving response: 15")
Log.d("TESTING", "suspend test after receiving response: 15")
Log.d("TESTING", "forEach iteration after calling test(): 15")
Log.d("TESTING", "response: 10")
Log.d("TESTING", "response: 15")
...
По сути, для каждого l oop перемещается и не ждет асинхронности API c ответ. Я думал, что .await()
предназначен для этого сценария, но я мог бы что-то упустить здесь, поскольку это явно не работает, как я себе это представлял.