Last active
May 24, 2020 22:16
-
-
Save 05nelsonm/4553b38805d70915fe497cdb456abc7e to your computer and use it in GitHub Desktop.
Library Dagger Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//////////// 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