Sobes.tech
Junior — Middle

How to perform two requests one after another, passing an authorization token, and get both results simultaneously?

sobes.tech AI

Answer from AI

To sequentially execute two requests with token passing and receive both results simultaneously, you can use coroutines or RxJava (in Android).

Example with Kotlin Coroutines and Retrofit:

suspend fun fetchData(token: String): Pair<Response1, Response2> {
    val response1 = api.getFirstData("Bearer $token")
    val response2 = api.getSecondData("Bearer $token")
    return Pair(response1, response2)
}

If you need to perform the requests in parallel and wait for both results:

suspend fun fetchDataParallel(token: String): Pair<Response1, Response2> = coroutineScope {
    val deferred1 = async { api.getFirstData("Bearer $token") }
    val deferred2 = async { api.getSecondData("Bearer $token") }
    Pair(deferred1.await(), deferred2.await())
}

In both cases, the token is passed in the authorization header. This approach allows you to get both results and process them together.