Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using coroutines in retrofit authenticator

I'm trying to implement JWT token authentication and refresh token in retrofit using coroutines. The tokens are stored in a Room database. How should I implement the await call?

Currently I'm using runBlocking {...} call to wait for the async local/remote response

Example:

client.addInterceptor {
        val accessToken = runBlocking { tokenRepository.getActiveToken() }?.access_token ?: "-"
        val request = it.request()
            .newBuilder()
            .addHeader("Authorization", "Bearer $accessToken")
            .build()
        return@addInterceptor it.proceed(request)
    }

What I'd like to follow is the traditional pattern of:

launch {
    withContext(IO){...}
}

How should I go about it?

like image 669
Mihirrai Avatar asked Jan 26 '19 02:01

Mihirrai


1 Answers

OkHttp is a Java library and uses synchronous request interceptors. Kotlin's coroutines aren't able to transform sync code into async, they just make your already async code look as simple as sync code. There was already a feature request in OkHttp to enable specifically what you ask for, but was declined. The reason is that, from the Java perspective, it makes a mess of the API and the implementation complexity is also very high.

Their recommendation is to handle this outside OkHttp, so in your case to first fetch the token in an async way and then initiate the HTTP request.

like image 112
Marko Topolnik Avatar answered Sep 20 '22 19:09

Marko Topolnik