答案 0 :(得分:1)
这是一个示例,您可以如何做。希望这会有所帮助。
@Module
class AppModule(val app: Context) {
@Provides
@Singleton
fun provideContext(): Context = app
@Provides
@Singleton
fun provideDatabase(context: Context): Database = Room.databaseBuilder(context, Database::class.java, "my_db").build()
@Provides
@Singleton
fun provideUserDao(database: Database): UserDao = database.userDao()
@Provides
@Singleton
fun providePostDao(database: Database): PostDao = database.postDao()
@Provides
@Singleton
fun provideCommentsDao(database: Database): CommentDao = database.commentDao()
@Provides
@Singleton
fun provideHttpLogging(): HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
@Provides
@Singleton
fun provideOkHttpClient(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient =
OkHttpClient.Builder().addInterceptor(loggingInterceptor).build()
@Provides
@Singleton
fun provideJackson(): JacksonConverterFactory = JacksonConverterFactory.create()
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient, jackson: JacksonConverterFactory): Retrofit = Retrofit.Builder()
.client(okHttpClient)
.baseUrl(baseUrl)
.addConverterFactory(jackson)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
@Provides
@Singleton
fun provideApiInterface(retrofit: Retrofit): ApiInterface = retrofit.create(
ApiInterface::class.java
)
}