4

I want to use regenerate token api in my android app with Retrofit. I was searching for solution how can i call regenerate token api when i get 401 response code from api. I found handy way of authenticator() method where i create instance of TokenAuthenticator class and this class has authenticate() overridden function under that i can call generate token api Which actually needs Retrofit builder Apiservice class. I am stuck in Circular dependency problem because TokenAuthenticator requires ApiServer and TokenAuthenticator() itself creates in Retrofit builder which returns ApiService. I found solutions on this problem using Dagger2 or hilt (Android Retrofit2 Refresh Oauth 2 Token). I am not using DI(Dagger2 or Hilt) in project. How can i pass ApiService to TokenAuthenticator() constructor. I also need to pass Preference(Jetpack datastore) to TokenAuthenticator() constructor because while calling regenerate api i am passing old token and other body.

How can i solve this problem can anyone help me please. thanks.

object RetrofitBuilder {

private const val BASE_URL = "..."
operator fun invoke(
    networkConnectionInterceptor: NetworkConnectionInterceptor
) : ApiService {
    val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor()
        .setLevel(HttpLoggingInterceptor.Level.BODY)

    val okkHttpclient = OkHttpClient.Builder()
        .authenticator(TokenAuthenticator())
        .addInterceptor(networkConnectionInterceptor)
        .addInterceptor(interceptor)
        .build()


    return Retrofit.Builder()
        .client(okkHttpclient)
        .baseUrl (BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build() //Doesn't require the adapter
        .create(ApiService::class.java)
}

}

  • Maybe just take a piece of paper and do your homework. Besides, there is no `TokenAuthenticator`... an if an `Interceptor` depends on `ApiService`, you're most likely doing it wrong. Hiding that fact by not showing us that class won't help. – Martin Zeitler Sep 10 '21 at 14:17
  • @MartinZeitler I have followed this answer https://stackoverflow.com/questions/37764670/android-retrofit-2-0-refresh-tokens. It is normal created class which extends Authenticator. you said if interceptor depends on ApiService i am doing wrong. So please guide me where i can get 401 and call regenerate token. I tried to create that class by class TokenAuthenticator(val sharedPrefsHelper: SharedPrefsHelper, private val identityService: IdentityService ) : Authenticator { override fun authenticate(route: Route?, response: Response): Request? { } – Sagar Ghare Sep 11 '21 at 06:21
  • If its wrong how this solution achieve this using Dagger (https://stackoverflow.com/questions/35516626/android-retrofit2-refresh-oauth-2-token/35630788#35630788). – Sagar Ghare Sep 11 '21 at 06:49
  • 1
    Please check this answer https://stackoverflow.com/questions/70633726/hilt-circular-dependency – Ruslan Leshchenko Jul 17 '23 at 06:15

0 Answers0