android – hilt – How can I update values after initialization

Published

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

Source: Android Questions

Published
Categorized as android, dagger-2, dagger-hilt, dependency-injection, kotlin

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq