我正在使用Hilt
并且我正在尝试创建和注入一个 Retrofit 客户端。
我的问题是我的一个改造客户需要一个SigningInterceptor(consumer)
我的消费者(OkHttpOAuthConsumer
)需要一个setTokenWithSecret(token, tokenSecret)
。
所以我的问题是如何Hilt
在创建我的改造客户端时传递信息(令牌和 tokenSecret)。
一些代码(可能更清楚):
我的ApiModule.kt
:
@InstallIn(ApplicationComponent::class)
@Module
object ApiModule {
//used to change URL dynamically
var url: String = "https://localhost"
@Provides
@Singleton
@Named("unsigned")
fun provideRetrofitClient(): Retrofit {
val interceptor = HttpLoggingInterceptor()
if (BuildConfig.DEBUG) {
interceptor.level = HttpLoggingInterceptor.Level.BODY
} else {
interceptor.level = HttpLoggingInterceptor.Level.NONE
}
val client = OkHttpClient.Builder()
.addInterceptor(interceptor)
.build()
return Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
.client(client)
.build()
}
@Provides
@Singleton
@Named("signed")
// The problem is here with those String
fun getClient(token: String, tokenSecret: String): Retrofit {
val interceptor = HttpLoggingInterceptor()
if (BuildConfig.DEBUG) {
interceptor.level = HttpLoggingInterceptor.Level.BODY
} else {
interceptor.level = HttpLoggingInterceptor.Level.NONE
}
consumer = OkHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
consumer.setTokenWithSecret(token, tokenSecret)
val client = OkHttpClient.Builder()
.addInterceptor(SigningInterceptor(consumer))
.addInterceptor(interceptor)
.build()
return Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
.client(client)
.build()
}
@Provides
@Singleton
fun provideLoginApi(
@Named("unsigned") retrofit: Retrofit
): LoginApiInterface =
retrofit.create(LoginApiInterface::class.java)
@Provides
@Singleton
fun provideUpdateDeviceApiInterface(
@Named("signed") retrofit: Retrofit
): UpdateDeviceApiInterface =
retrofit.create(UpdateDeviceApiInterface::class.java)
}
我的Repository
:
class MyRepository @Inject constructor(
...
private var updateDeviceApiInterface: UpdateDeviceApiInterface,
...
) {
...
}
我的ViewModel
:
class MyViewModel @Inject constructor(
private var myRepository: MyRepository
) :
ViewModel() {
...
}
最后我的Fragment
:
@AndroidEntryPoint
class MyFragment : Fragment() {
...
@Inject
lateinit var myViewModel: MyViewModel
...
}
(我对第一个改造客户端@Named(unsigned)
没有问题,所以使用 LoginApiInterface 没有问题)。