直接开始,首先我们看看怎么使用Hilt编写Retrofit接口请求类
用@Provides注解定义可注入的实例的提供者函数,如:provideHttpClient()用于提供OkHttpClient的实例,provideRetrofit()用于提供Retrofit实例,provideUserService()用于提供UserService的实例,这样我们就可以在其他的类里用@Inject获取注入该实例了。
完整代码:
@Module
@InstallIn(SingletonComponent::class)
/** 单例 */
object RetrofitModule {
/** 服务地址 */
private const val BASE_URL = Constant.SERVER_ADDRESS
/** 提供OkHttpClient */
@Singleton
@Provides
fun provideHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(LoggingInterceptor())
.addInterceptor(HeaderInterceptor())
.addInterceptor(BasicParamsInterceptor())
.build()
}
/** 提供Retrofit */
@Singleton
@Provi