Reputation: 394
I'm trying to refactor one of my very first (poorly written) projects using Hilt. Unfortunately of all tutorials I've seen, no one covers this pretty basic case: provide username and password for retrofit basic authentication.
I've set up the network module, but rightly the compiler complains about "not be able to inject the String parameters" for the "provideRetrofitClient" function. Parameters that I would like to pass from the viewmodel
ViewModel:
@HiltViewModel
class AuthenticationViewModel
@Inject
constructor(
private val apiService: ApiService
) : ViewModel() {
performLogin(username:String,password:String){
viewModelScope.launch {
//how can I pass credentials to apiService?
apiService.login()
}
}
NetworkModule:
Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Singleton
@Provides
fun provideGsonBuilder(): Gson = GsonBuilder().setLenient().create()
@Singleton
@Provides
fun provideRetrofitClient(username: String, password: String): OkHttpClient {
return OkHttpClient.Builder()
//this intercemptor allowed credentials set up in the original app
//.addInterceptor(BasicAuthInterceptor(username, password))
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build()
}
@Singleton
@Provides
fun provideRetrofitBuilder(gsonBuilder: Gson, client: OkHttpClient): Retrofit.Builder {
return Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gsonBuilder))
.client(client)
}
@Singleton
@Provides
fun provideApiService(retrofitBuilder: Retrofit.Builder): ApiService {
return retrofitBuilder
.build()
.create(ApiService::class.java)
}
How can the injected retrofit client be "configured" with credentials at runtime?
Upvotes: 0
Views: 620
Reputation: 11
NetworkModule very likely should not have username/password parameters for the provideRetrofitClient
function. This function should just create the service and allow it to be injected where you need it.
If your API requires username & password as query parameters on the request then the username & password should be provided via ApiService's
login
function as login(@Query("username") username: String, @Query("password") password: String)
. Note - the string value inside the query annotation is dependent on what query parameters the API expects.
If your API requires username & password in the body or path, then have a look at the https://square.github.io/retrofit/ for examples on how your login
function should be.
You can then pass the username & password from your viewModel function performLogin
.
Upvotes: 1