0

I was using Koin as dependency Injection library to create the ktor HttpClient:

val AppModule = module {
    single { provideClientService() }
}

fun provideClientService(preferences: SharedPreferences): HttpClient {

install(Auth){
    bearer {
        loadTokens {
            BearerTokens(sharedPreferences.getString("accessToken",""))      
        }
    }
}}

but after the user login the accessToken is not updated.

I think it is because of the different scopes in koin. there is 3 kind of scopes in koin:

  • single definition : create an object that persists with the entire container lifetime (can't be dropped).

  • factory definition : create a new object each time. Short life. No persistence in the container (can't be shared).

  • scoped definition : create an object that is persistent tied to the associated scope lifetime.

so I changed the client definition to factory , because I want it to be updated after getting a new token. and now I wonder is it correct?

val AppModule = module {
    factory { provideClientService() }
}
  • The single definition should be enough here because the description doesn't say anything about updates of an object's internal state. Could you please describe how an access token is updated? – Aleksei Tirman Nov 14 '22 at 08:32
  • you are right, I edited my post. I get accessToken from preferences which is null before login and then get updated. – Maryam Memarzadeh Nov 14 '22 at 08:47
  • The handler for `loadTokens` is called only when an access token isn't loaded yet. An access token can be updated if it should be refreshed (the `refreshTokens` method) or the token's storage is cleared (https://stackoverflow.com/a/69993453/13963150). Please tell me in what case you experience a problem. – Aleksei Tirman Nov 14 '22 at 09:53
  • before you login to your app accessToken is empty and after login I wanted my accessToken to be added to my ktor Client but because I defined it as single it doesn't create a new client object so the accessToken remained empty and I get unAutherized error. – Maryam Memarzadeh Nov 16 '22 at 03:45
  • Unfortunately, I cannot reproduce your problem. Please see the gist with a code https://gist.github.com/Stexxe/43bb6b1461c5dc1ad045b94e673ddcc0 – Aleksei Tirman Nov 16 '22 at 08:05

0 Answers0