2

I am having multiple api calls going in a screen launched with viewmodel scope like this in viewmodel

viewModelScope.launch {
    apiCallOne()
}

viewModelScope.launch {
    apiCallTwo()
}

viewModelScope.launch {
    apiCallThree()
}

And my auhtenticator is

override fun authenticate(route: Route?, response: Response): Request? {

    return if (response.retryCount < 1) {
        val token = refreshToken()
        if (token != null)
            response.request.newBuilder().header("Authorization", "Bearer $token")
                .build()
        else
            null
    } else {
        navigateToOnboardingActivity()
        null
    }


}

It is working fine but when 3 api calls are launched parallely , the session is getting refreshed 3 times, how can i make it work like if apicallOne() get 401, it will got to autnenticator and call refresh token api, in this time apicallTwo() and apicallThree() should paused and resumed after the first authenticaor gets successfull response.

Please note i cant call all apis in single launch like this

viewModelScope.launch{
apiCallOne()
apiCallTwo()
apiCallThree()
}
Harish Padmanabh
  • 307
  • 4
  • 17
  • I am looking into the same issue. I have found an [article](https://medium.com/@emmanuelguther/android-refresh-token-with-multiple-calls-with-retrofit-babe5d1023a1) which suggest making the block inside authenticate synchronized so it cannot be executed in parallel. – argenkiwi Mar 08 '23 at 22:37

1 Answers1

1

you can use like this example:

viewModelScope.launch{
 val result1 = async{apiCallOne()}.await()
 
 if (result1.code() != 401) {
    apiCallTwo()
    apiCallThree()
 }
}

or this:

viewModelScope.launch{
     val result1 = withContext(Dispatchers.Default) {apiCallOne()}
     
     if (result1.code() != 401) {
        apiCallTwo()
        apiCallThree()
     }
    }