Reputation: 414
I'm working in a project and I need to inject Retrofit object with Dagger 2. I search info but I only have been able to do a few steps and now I don't know how to continue:
My component:
@Singleton
@Component(modules = arrayOf(NetworkModule::class))
interface NetworkComponent {
fun inject(foo: TheApplication)
}
My module:
@Module
class NetworkModule {
@Provides
@Singleton
fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://api.chucknorris.io/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
}
And now I see I have to make a Class
who extends from Application
for init the Component
and make an @Inject
next:
class TheApplication: Application() {
override fun onCreate() {
super.onCreate()
val net: NetworkModule = Dagger...
}
}
Theoretically when I put the Dagger...
it should be DaggerNetworkComponent
but I rebuild project and still missing.
Anyone can explain to me for what is the Application.class
made for and how I can continue?
Upvotes: 7
Views: 4625
Reputation: 5043
Try this
AppComponent.kt
@Component(modules = [NetworkModule::class])
@Singleton
interface AppComponent {
fun inject(app: MyApp)
}
NetworkModule.kt
@Module
class NetworkModule {
@Singleton
@Provides
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("YOUR_BASE_URL")
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
@Singleton
@Provides
fun provideApi(retrofit: Retrofit): WebApi {
return retrofit.create(WebApi::class.java)
}
@Singleton
@Provides
fun provideOkHttpClient(
interceptors: ArrayList<Interceptor>
): OkHttpClient {
val clientBuilder = OkHttpClient.Builder()
.followRedirects(false)
interceptors.forEach {
clientBuilder.addInterceptor(it)
}
return clientBuilder.build()
}
@Singleton
@Provides
fun provideInterceptors(): ArrayList<Interceptor> {
val interceptors = arrayListOf<Interceptor>()
val loggingInterceptor = HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Level.BODY
} else {
HttpLoggingInterceptor.Level.NONE
}
}
interceptors.add(loggingInterceptor)
return interceptors
}
}
MyApp.kt
class MyApp : Application() {
companion object {
lateinit var instance: MyApp
private set
}
lateinit var appComponent: AppComponent
private set
override fun onCreate() {
super.onCreate()
instance = this
initComponent()
}
private fun initComponent() {
appComponent = DaggerAppComponent.builder()
.build()
appComponent.inject(this)
}
}
AndroidManifest.xml
<application
android:name=".MyApp"
....
Upvotes: 7