我不知道如何注入网络模块。我尝试并找到了用匕首2注入网络模块的多种方法,但我无法解决。请帮帮我。
abstract class BaseRepository protected constructor() {
init {
val logger = HttpLoggingInterceptor()
logger.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.addInterceptor(logger)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(Gson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build()
mTheApi = retrofit.create<AttendanceApi>(AttendanceApi::class.java)
}
}
我尝试了这个模块,但是没有用。
class NetworkModule {
companion object {
private const val NAME_BASE_URL = "NAME_BASE_URL"
}
@Provides
@Named(NAME_BASE_URL)
fun provideBaseUrlString()=
"http://attendance.saltcloudserver.com/api/"
@Provides
@Singleton
fun provideHttpClient()=OkHttpClient()
@Provides
@Singleton
fun provideRetrofit(interceptor: HttpLoggingInterceptor): OkHttpClient {
return OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build()
}
}
我期望输出,但是我不能注入。
答案 0 :(得分:0)
要识别匕首,您需要指定它是Module
。为此,您需要向该类中添加@Module
批注,我发现当前的实现中缺少该批注。
@Module
class NetworkModule {
companion object {
private const val NAME_BASE_URL = "NAME_BASE_URL"
}
@Provides
@Named(NAME_BASE_URL)
fun provideBaseUrlString()=
"http://attendance.saltcloudserver.com/api/"
@Provides
@Singleton
fun provideHttpClient()=OkHttpClient()
@Provides
@Singleton
fun provideRetrofit(interceptor: HttpLoggingInterceptor): OkHttpClient {
return OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build()
}
}