Hello guys, in our team we're tired of dagger 2 on...
# koin
t
Hello guys, in our team we're tired of dagger 2 on android, that "rebuild all the things" and "wow much boilerplate, so verbose" stuff. I like koin it seems nice to me, but how can I do java interop with it? Any tips?
l
You can create an interface with a single method that provides a dependency. This method will lazily load it using Koin.
Kotlin code:
Copy code
interface DependencyProvider<out T>: KoinComponent {
    fun provide(): T
}

fun <T: Any> provideDependency(clazz: KClass<T>): DependencyProvider<T> {
    return object: DependencyProvider<T> {
        override fun provide(): T {
            val koinContext = StandAloneContext.koinContext as KoinContext
            val resolver: () -> BeanDefinition<*> = { koinContext.beanRegistry.searchAll(clazz) }
            return koinContext.resolveInstance(clazz, resolver)
        }

    }
}
And the Java code:
Copy code
public class JavaClass {
    private DependencyProvider<TasksDao> tasksDaoDependencyProvider = AppExecutorsKt.provideDependency(kotlin.jvm.JvmClassMappingKt.getKotlinClass(TasksDao.class));
}
a
@themishkun did you managed to bring Koin to your java app?
t
@arnaud.giuliani Not yet, we are actively discussing it, examples above gave us some insights. We are practically 50/50 Java to Kotlin ratio right now, the project is rather old, so we need to figure out the way to migrate smoothly, not touching scary beasts hiding in legacy code
@arnaud.giuliani maybe you know more pleasant way for Java interop?
a
@themishkun to be honest, Java interop was not in the 1st features to develop for Koin. We were focused on Kotlin feature and how to easily write things
But you can open an issue and we will see how we can help you - and if we need to patch Koin for your Java usage
t
@arnaud.giuliani and it worked out well, I wish I could start from scratch and throw out all Java code just to write things easily
a
😄
I think you will have to describe your content with Kotlin Koin modules
the idea will be to try to use Your java classes to inject
but I never tested injection in activities/fragments without Kotlin
Do know yet the final syntax for java
@themishkun I think one strategy will be to write as much as possible in Kotlin
make all your DI in Kotlin
and for Java Android Components (Activities ...) write a dependency holder