Reputation: 175
I am trying to call a method from the datastore with flow inside an interceptor, but it doesn't work.
What is the correct way to do it?
Here I define my interceptor
class AuthorizationInterceptor @Inject constructor(
@ApplicationContext private val appContext: Context,
) : HttpInterceptor {
private val authPreferences = AuthPreferences(appContext)
override suspend fun intercept(
request: HttpRequest,
chain: HttpInterceptorChain
): HttpResponse {
// here I try to get the token
var tokenString = "";
authPreferences.getAccessToken.collect { token ->
tokenString = token
}
return chain.proceed(request.withHeader("Authorization", "Bearer $tokenString"))
//return chain.proceed(request.withHeader("Authorization", "Bearer 1111"))
}
}
Here I define my Store
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("auth_pref");
class AuthPreferences(private val context: Context) {
companion object {
val AUTH_ACCESS_TOKEN = stringPreferencesKey(name = "auth_access_token")
val AUTH_REFRESH_TOKEN = stringPreferencesKey(name = "auth_refresh_token")
}
suspend fun saveAccessToken(token: String) {
context.dataStore.edit { preferences ->
preferences[AUTH_ACCESS_TOKEN] = token
}
}
val getAccessToken: Flow<String> = context.dataStore.data
.map { preferences ->
preferences[AUTH_ACCESS_TOKEN] ?: ""
}
suspend fun saveRefreshToken(token: String) {
context.dataStore.edit { preferences ->
preferences[AUTH_REFRESH_TOKEN] = token
}
}
val getRefreshToken: Flow<String> = context.dataStore.data
.map { preferences ->
preferences[AUTH_REFRESH_TOKEN] ?: ""
}
}
I think my problem is with flows
Upvotes: 2
Views: 967
Reputation: 172
You can use it same that
val getRefreshToken =runBlocking { session.getRefreshToken() }
and after that you can use it.
Upvotes: 0