Skip to content

Instantly share code, notes, and snippets.

@05nelsonm
Last active May 24, 2020 22:16
Show Gist options
  • Save 05nelsonm/4553b38805d70915fe497cdb456abc7e to your computer and use it in GitHub Desktop.
Save 05nelsonm/4553b38805d70915fe497cdb456abc7e to your computer and use it in GitHub Desktop.
Library Dagger Implementation
//////////// Library user's Application class ////////
class App: Application() {
override fun onCreate() {
initMyLibrary()
}
private fun initMyLibrary() {
MyLibrary.Builder()
.setApplication(this)
.someMethodA(true)
.someMethodB(true)
.build()
}
}
///////////////////////////////////////////////////////
sealed class MyLibrary {
class Builder {
fun setApplication(application: Application): InnerBuilder {
val componenet = applicationComponent
.builder()
.bindApplication(application)
.build()
val injectedClasses = InjectedClasses(applicationComponent)
return InnerBuilder(component, injectedClasses)
}
// this is our entry point for testing, instead of using the setApplication method
// that way we have access to the entire graph via our TestApplicationComponent
class InnerBuilder(
applicationComponent: ApplicationComponent,
injectedClasses: InjectedClasses
) {
// Set private companion object variables to be used
// by LibraryAPI classes.
init {
appComponent = applicationComponent
injected = injectedClasses
}
private var optionAlphaInitValue = false
private var optionBetaInitValue = true
fun someMethodA(): InnerBuilder {
// do something with optionAlphaInitValue
return this
}
fun someMethodB(): InnerBuilder {
// do something with optionBetaInitValue
return this
}
fun build() {
injected.someClass1.setREKT(optionAlphaInitValue)
injected.someClass2.somethingElse(optionBetaInitValue)
}
}
}
private companion object {
lateinit var appComponent: ApplicationComponent
lateinit var injected: InjectedClasses
}
// class gets instantiated by library user via MyLibrary.LibraryAPI().
// All the other classes that are injected aren't available because they're
// in the private companion object. Sure, the library user can instantiate another
// instance of that class, but they won't have access to the one that was initialized
// within MyLibrary.
class LibraryAPI() {
fun getREKT(boolean: Boolean): String =
return injected.someClass1.something(boolean)
}
}
class InjectClasses(appComponent: ApplicationComponent) {
init {
appComponent.inject(this)
}
@Inject lateinit var someClass1: SomeClass1
@Inject lateinit var someClass2: SomeClass2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment