I have some problem with suspend in a Interceptor. I use a interceptor to refresh token: ``` @Single...
a
I have some problem with suspend in a Interceptor. I use a interceptor to refresh token:
Copy code
@Singleton
class RefreshInterceptor @Inject
constructor(
 private val savePrefSecurity: SavePrefSecurity
) : Interceptor {
   
    override fun intercept(chain: Interceptor.Chain): Response {

       
        var request = chain?.request()
        var response = chain!!.proceed(request)
           if (response.code == 401) {
            var refresh = savePrefSecurity.getSValue(REFRESH_TOKEN)
            if (!refresh.isNullOrBlank()) {
                )
                GlobalScope.launch {
                    var refrehResponse = api.refreshToken(sendRefresh)
                    [....}
                    // other code...
                     return@let intercept(chain)
                }
            }
}
   return response
1. how can i avoid GlobalScope ? because refreshToken is a supend function 2. i think that return@let intercept(chain) is inappropriate blockin
1
l
Good question! You can defined an interface which have the refreshtoken mechanism. This interface can be implemented in the specific scope (fragment, activity, or viewModel) -> you don’t need to use the GlobalScope here
a
You could potentially just inject a scope into the RefereshInterceptor and then use that. This way you get to control what get's injected and then will make testing easier since you can decide to whatever you need for testing
o
runBlocking
. OkHttp takes care of background threading. You won't block the main thread. On the contrary, when many requests fail with 401 you'll needlessly refresh the token each time (but more probably your backend will reject the refresh token as stale, won't it?) if you don't utilize a
Mutex
or something similar.
1
958 Views