Created
September 14, 2018 12:41
-
-
Save ValeryPonomarenko/88d9d782f39c19be7cb4a15fbdbe6c1a to your computer and use it in GitHub Desktop.
Lifecycle aware dagger components
This file contains 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
class InjectionManager { | |
companion object { | |
@JvmStatic val instance = InjectionManager() | |
} | |
private val componentsStore = ComponentsStore() | |
fun init(app: Application) { | |
app.registerActivityLifecycleCallbacks(ActivityLifecycleHelper(componentsStore)) | |
} | |
@Suppress("UNCHECKED_CAST") | |
fun <T> bindComponent(owner: IHasComponent): T = | |
getComponentOrCreate(owner.getComponentKey(), owner) as T | |
inline fun <reified T> findComponent(): T = | |
findComponent { it is T } as T | |
fun findComponent(predicate: (Any) -> Boolean): Any = | |
componentsStore.findComponent(predicate) | |
private fun getComponentOrCreate(key: String, owner: IHasComponent): Any { | |
return when { | |
componentsStore.isExist(key) -> componentsStore.get(key) | |
else -> owner.getComponent().also { componentsStore.add(key, it) } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment