Some Friendly Dagger Samples
Let's see how we can set up Dagger, what are the different configurations we can choose from and what will each offer. I wanted a sandbox to help myself and hopefully others. Please let me know if I can improve something or add an additional setup :) thank you for checking this out!
First things first!
- it abstracts how we construct our dependencies
- constructor injection forces us to write better code that is testable
- we get scoping of our dependencies
The most basic dagger configuration comprising of just an application component that provides a retrofit service.
Check out the DI Package. There you will see the Application Component and the Application Module
Here is a basic Component that gives us our dependencies (a retrofit service), a convenience method for building the component, and a way to pass in parameters to our dependencies
@Singleton
@Component(modules = [ApplicationModule::class])
interface ApplicationComponent {
@Component.Builder
interface Builder {
// convenience method to help us build the component
fun build() : ApplicationComponent
// we pass in our endpoint url to make it available to the module
@BindsInstance
fun endpoint(endpointUrl: String) : Builder
}
fun inject(mainActivity: MainActivity)
// we don't have to use inject() above, we can
// get the BookService this way as well
fun bookService() : BookService
}
We provide our dependencies, in this case a retrofit service, from the module
@Module
object ApplicationModule {
@JvmStatic
@Provides
@Singleton
fun provideRetrofit(openLibraryUrl: String) : BookService = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create())
.baseUrl(openLibraryUrl)
.build()
.create(BookService::class.java)
}
Building the Application Component in our BookApplication
class BookApplication : Application() {
lateinit var applicationComponent: ApplicationComponent
override fun onCreate() {
super.onCreate()
applicationComponent = DaggerApplicationComponent.builder()
.endpoint("https://openlibrary.org/")
.build()
}
}
Accessing the Application Component to get our retrofit service in MainActivity
@Inject
protected lateinit var bookService: BookService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(applicationContext as BookApplication).applicationComponent.inject(this)
}
or
val bookService = (applicationContext as BookApplication).applicationComponent.bookService()