Easy Android Dependency Injection with Koin

What are find it in Koin not in Dagger?
1- Runtime, lightweight service locator.
2- No code generation.
3- Easy to use in your code.
4- Based in kotlin feature.
5- Written fully in kotlin and works in kotlin classes only.
How to use Koin?
1- Gradle Setup
// Add Jcenter to your repositories if needed
repositories {
jcenter()
}
dependencies {
// Koin for Android
compile 'org.koin:koin-android:2.0.1'
}2- Our components (Java & Kotlin)
interface HelloRepository {
fun giveHello(): String
}
class HelloRepositoryImpl() : HelloRepository {
override fun giveHello() = "Hello Koin"
}Let’s create a Java presenter class, for consuming this data:
public class MyJavaPresenter {
private HelloRepository repository;
public MyJavaPresenter(HelloRepository repository) {
this.repository = repository;
}
public String sayHello(){
String hello = repository.giveHello();
return hello+" from "+this;
}
}3- Writing the Koin module
Use the module function to declare a module. Let’s declare our first component:
val appModule = module {
// single instance of HelloRepository
single<HelloRepository> { HelloRepositoryImpl() }
// Simple Presenter Factory
factory { MyJavaPresenter(get()) }
}4- Start Koin
Now that we have a module, let’s start it with Koin. Open your application class, or make one (don’t forget to declare it in your manifest.xml). Just call the startKoin() function:
class MyApplication : Application(){
override fun onCreate() {
super.onCreate()
// Start Koin
startKoin{
androidLogger()
androidContext(this@MyApplication)
modules(appModule)
}
}
}5- Injecting dependencies into Java Activity
The MyJavaPresenter component will be created with HelloRepository instance. To get it into our Activity, let’s inject it with the static inject() function:
// import inject
import static org.koin.java.standalone.KoinJavaComponent.inject;
public class JavaActivity extends AppCompatActivity {
private Lazy<MySimplePresenter> presenter = inject(MySimplePresenter.class);
private Lazy<MyJavaPresenter> javaPresenter = inject(MyJavaPresenter.class);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
//...
}
}The inject() function allows us to retrieve a lazy Koin instances, in Android components runtime (Activity, fragment, Service…)
The get() function is here to retrieve directly an instance (non lazy)
You can check this simple in github
