Home > Mobile >  android - hilt - How can I update values after initialization
android - hilt - How can I update values after initialization

Time:11-29

In my app, the user can log in from any fragment and so after login if I send any request to the server, the new token didn't send. for example, if the user login from fragment A and send a request the new token for the user didn't send with the headers. because hilt viewModel is created and the token value == null

how can I refresh any value I injected before?

@Module
@InstallIn(ActivityRetainedComponent::class)
object NetworkModule {

@Provides
fun provideMainRepository(): MainRepository {
    return MainRepository()
}


@Provides
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
    return Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(BuildConfig.BASE_URL)
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
   .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
        .build()
}


@Provides
fun provideOkHttpClient(token:String): OkHttpClient {
    val okHttpClient = OkHttpClient.Builder()
    okHttpClient.addInterceptor(HttpRequestInterceptor(token))
    return okHttpClient.build()
}

@Provides
fun provideToken(@ApplicationContext context: Context): String {
    return context.getToken()
}

@Provides
fun provideDataService(retrofit: Retrofit): DataService {
    return retrofit.create(DataService::class.java)
}

}

my ViewModel

@HiltViewModel
class ProductsCategoryViewModel @Inject constructor(
private val service: CartService, private val mainRepository: MainRepository
) : BaseViewModel() {}

so how can I update the token after injected values created

CodePudding user response:

You can't update it via injection. Injection happens at instantiation, injection never updates anything. What you can do is instead of injecting a Token, you inject a User which has a nullable property token: Token? the client code can query with getToken() to return the current token, and that your login system can update with the current token when the user logs in. In this scenario User should be a singleton via injection scoping, so the login system can update the only instance of the class.

  • Related