https://kotlinlang.org logo
#koin-contributors
Title
# koin-contributors
e

Emanuel Moecklin

12/23/2022, 1:02 PM
I use
fragmentFactory()
to inject Fragments into Activities and that works like a charm. I was wondering if I could use an
AppComponentFactory
to do the same for Activities and made a quick prototype:
Copy code
val componentFactoryModule = module {
    single<AppComponentFactory> { KoinComponentFactory() }
}

fun KoinApplication.componentFactory() {
    koin.loadModules(listOf(componentFactoryModule))
}

class KoinComponentFactory : AppComponentFactory(), KoinComponent {

    override fun instantiateActivity(
        cl: ClassLoader, className: String, intent: Intent?
    ): Activity {
        val clazz = Class.forName(className).kotlin
        val instance: Activity? = getKoin().getOrNull(clazz)
        return instance ?: super.instantiateActivity(cl, className, intent)
    }

}
add to startKoin:
Copy code
startKoin {
    componentFactory()
    ...
and register the factory in the manifest:
Copy code
tools:replace="android:appComponentFactory"
   android:appComponentFactory="mypackage.KoinComponentFactory"
This also works like a charm and I would love this to be part of the library itself but I'm not sure if this is the way to go and how this needs to be changed to play nicely with scopes?
a

arnaud.giuliani

12/28/2022, 8:31 AM
Interesting idea. I would need to dive a bit more deeper to see limits of the API
17 Views