Jitendra
09/15/2022, 4:48 AMmattinger
09/21/2022, 3:42 AMinterface MyInjectors {
fun inject(activity: MyActivity)
@Component(...)
fun MyComponent: MyInjectors {
...
}
I then use this custom class to hold components and retrieve whatever registered component implements the requested interface. when i created the component, i register it with this registry.
object ComponentRegistry {
@PublishedApi
@Suppress("ObjectPropertyNaming")
internal val _components = mutableSetOf<Any>()
fun add(component: Any) {
_components.add(component)
}
fun remove(component: Any): Boolean =
_components.remove(component)
val size: Int
get() = _components.size
fun clear() = _components.clear()
inline fun <reified T> hasComponent() =
_components
.filterIsInstance<T>()
.isNotEmpty()
inline fun <reified T> getOrNull(): T? =
_components
.filterIsInstance<T>()
.singleOrNull()
inline fun <reified T> get(): T =
_components
.filterIsInstance<T>()
.single()
inline fun <reified T> replace(component: Any) {
getOrNull<T>()?.let { remove(it) }
add(component)
}
}
And at your injection point:
ComponentRegistry.get<MyInjectors>().inject(this)
mattinger
09/21/2022, 3:45 AM