WaheedNazir/Kotlin-MVVM-Architecture

How to add interceptor in retrofit in this project

Rohitsachdeva opened this issue · 2 comments

I want to refresh my token when it expires, for that I need to change in everycall and need to add login method in every Repo. for that I have studied that interceptor can fix it. please explain how to add this into it.

Hi @Rohitsachdeva You can update provideNewsService() function content with the below code and add your interceptors or you can use DI to return your client from separate method.

val client: OkHttpClient = OkHttpClient.Builder().addInterceptor(Interceptor { chain ->
            val request: Request = chain.request()
            val newReq: Request = request.newBuilder()
                .addHeader("Authorization", format("token %s", "your token"))
                .build()
            chain.proceed(newReq)
        }).build()

        return Retrofit.Builder()
            .client(client)
            .baseUrl(BuildConfig.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(LiveDataCallAdapterFactoryForRetrofit())
            .build()
            .create(ApiServices::class.java)

I have to refresh my token, but not able to find how can I do the same.