how to use Authenticator with suspend api function? Retrofit

Viewed 1305

I am building client:

OkHttpClient().newBuilder()
        .authenticator(object : Authenticator {
        override fun authenticate(route: Route?, response: Response): Request? {
            val request = AppPreferences.refreshToken?.let {
                api.refreshTokenC(it).execute()
            }
            
         ...
        })

and for this I use usual fun which returns Call :

@POST("Accounts/refresh")
fun refreshTokenC(@Query("refreshToken") refreshToken: String): Call<TokenResponse>

But how can use it with suspend function?:

    @POST("Accounts/refresh")
suspend fun refreshToken(@Query("refreshToken") refreshToken: String): Response<TokenResponse>
1 Answers
  • fun authenticate(route: Route?, response: Response) is not suspend function, we cannot invoke suspend function from it.

  • Can use runBlocking:

Runs a new coroutine and blocks the current thread interruptibly until its completion. This function should not be used from a coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.

  • fun authenticate(route: Route?, response: Response) is being called on a background thread, we can use runBlocking safely.
val request = AppPreferences.refreshToken?.let { token ->
    runBlocking { api.refreshToken(token) }
}

Similar code: AuthInterceptor.kt

Related