I am trying to retrieve data from an api using retrofit. The request am going to use needs an access token to pass in the header. The problem is that the token expires after 10 min and the refresh token request needs an unexpired token to create a new one! So what should i do to keep the token refreshed by it self before passing 10 min? I already tried Interceptor but it can't work with this type of problem because i need a valid token to get a new one
1
votes
the way you will use an interceptor is by intercepting the first failed request from retrofit and then doing a refresh token method on the spot and replacing your old API request with a new one with the newly created token, and then you will do a retry, this all happens inside the interceptor and can be quite buggy and hard to maintain, take a look at my answer and let me know if you need further help
- Mahmoud Omara
1 Answers
0
votes
You can use a Worker and set it to run every 30min or so and set it to save the renewed token in your SharedPreference
here's an example for the Worker
class UpdateTokenWorkManger(
val context: Context,
params: WorkerParameters) : Worker(context, params) {
override fun doWork(): Result {
LoginHandler.refreshTokenSilently()
// Indicate whether the work finished successfully with the Result
return Result.success()
}
companion object {
private const val TAG = "Token Refresh "
const val TOKEN_REFRESH_WORK_MANGER_ID = "automatic_renew_token_work_manger"
fun renewToken() {
val periodicRefreshRequest = PeriodicWorkRequest.Builder(
UpdateTokenWorkManger::class.java, // Your worker class
30, // repeating interval
TimeUnit.MINUTES
)
val periodicWorkRequest: PeriodicWorkRequest = periodicRefreshRequest
.build()
WorkManager.getInstance(App.getApplication()).enqueueUniquePeriodicWork(
TOKEN_REFRESH_WORK_MANGER_ID,
ExistingPeriodicWorkPolicy.REPLACE,
periodicWorkRequest
)
}
}
to use this component you will need these dependencies
implementation "androidx.work:work-runtime-ktx:2.4.0"
also note that LoginHandler is the class that should be responsible for handling your login, refresh and logout scenarios.
and don't forget to add this line to your first Activity after the login Activity, for example: if you login in SplashActivity and after succesful authentication you redirect to MainActivity, then this line should be in MainActivity's onCreate function
UpdateTokenWorkManger.renewToken()