Вы можете сделать это с помощью Сопрограммы вместе с Потоком примерно так:
Превратите обратных вызовов в приостановленных функций с блоком suspendCancellableCoroutine {...}
:
suspend fun <T> request(requestBuilder: RequestBuilder): T = suspendCancellableCoroutine { cont ->
Server.asyncRequest(requestBuilder) { resource: T, error: ServiceError? ->
if(error != null)
cont.resumeWithException(error) // Makes the Flow throw an exception
else
cont.resume(resource) // Makes the Flow emit a correct result
}
}
Создание Flow для выполнения первого запроса :
val resourceOneFlow = flow {
emit(request<String>(RequestBuilder(endpoints.second, ids, params)))
}
Создание Поток для выполнения второго запроса :
val resourceTwoFlow = flow {
emit(request<String>(RequestBuilder(endpoints.third, ids, params)))
}
Объединение обоих Потоки с оператором zip
:
val requestsResultFlow = resourceOneFlow.zip(resourceTwoFlow) { resourceOne, resourceTwo ->
// Build whatever you need with resourceOne and resourceTwo here and let it flow
"$resourceOne $resourceTwo".length // Here I concatenate both strings and return its length
}
Активируйте / запустите Flow с оператором collect
и используйте его результат :
requestsResultFlow.collect { length ->
// Consume the result here
println("$length") // Here I print the number received
}
У вас есть Поток Документация Здесь .