使用Dagger 2进行改装-Android

时间:2018-11-26 14:48:19

标签: android retrofit2 dagger-2

我正在使用以下样品:

New Android Injector with Dagger 2

如何在此类SQLite Connection中定义我的retrofitAppModule等...

1 个答案:

答案 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
    )
}