Skip to content

Instantly share code, notes, and snippets.

@ValeryPonomarenko
Created September 14, 2018 12:41
Show Gist options
  • Save ValeryPonomarenko/88d9d782f39c19be7cb4a15fbdbe6c1a to your computer and use it in GitHub Desktop.
Save ValeryPonomarenko/88d9d782f39c19be7cb4a15fbdbe6c1a to your computer and use it in GitHub Desktop.
Lifecycle aware dagger components
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