In this presentation i have talked about two frameworks that we can use to handle Dependency Injection in Android projects: Koin, Dagger. There's a short introduction and then i will use a sample to analyze the difference between them.
7. What is Koin?
Koin is a lightweight dependency injection
framework for Kotlin Developers.
● Written in pure Kotlin
● No proxy
● No code generation
● No reflection
15. ViewModelFactory
For building custom ViewModel classes
with argument-passing constructors
(e.g. for passing custom data or @Inject
annotated constructors), we must
provide a class that extends
ViewModelProvider.Factory, returning
instances of our custom ViewModels into
the create() method
16. ViewModelModule
Dagger 2 can associate a Provider to a given type, and inject it into a Map. This is possible
using @IntoMap on a method that provides a value with a given type, and in our case it
provides a Class which extend ViewModel. The key is provided by a custom annotation
@ViewModelKey.
17. ViewModelKey
The key is provided by a custom annotation @ViewModelKey , annotated using @MapKey
where we’re specifying as type of our key KClass<out ViewModel>
20. Koin DSL
● get() : request needed component instance.
● factory() : declare a factory instance component
(new instance on each demand).
● single() : declare a singleton instance component
(unique instance).
● name = : is used to name definitions.
21. ViewModel DSL extension allow to
declare a viewModel -
be later inject into Activity/Fragment with
dedicated injector.
22. Ready to Inject
The by viewModel() function allows us to retrieve a ViewModel instance from Koin,
linked to the Android ViewModelFactory.
25. Conclusion
- Koin don’t require any special Android classes
nor any introspection.
- No need to write custom annotation to match
your need.
- no need to regenerate & recompile
- it’s easier to understand