Pular para o conteúdo principal

Koin Examples - Kotlin Android

Koin is a lightweight dependency injection framework for Kotlin. It is designed to be simple and easy to use while still providing all the features you need to manage your dependencies. Koin is an alternative to other popular frameworks such as Dagger, which can be complex to learn and use. In this article, we will explore how to use Koin in Android.

Step 1: Add Koin to your project

The first step is to add Koin to your project. You can do this by adding the following lines to your build.gradle file:

repositories {
maven { url 'https://oss.jfrog.org/artifactory/oss-snapshot-local' }
}

dependencies {
implementation 'org.koin:koin-android:3.0.1-SNAPSHOT'
implementation 'org.koin:koin-android-scope:3.0.1-SNAPSHOT'
implementation 'org.koin:koin-android-viewmodel:3.0.1-SNAPSHOT'
}

Step 2: Create a Koin module

The next step is to create a Koin module. A module is a collection of dependencies that can be injected into your application. You can create a module by creating a Kotlin file and defining your dependencies like this:

val myModule = module {
single { MyDependency() }
factory { MyFactory() }
}

In this example, we define two dependencies: a single instance of MyDependency and a factory for MyFactory. The difference between a single and a factory is that a single creates only one instance of the dependency, while a factory creates a new instance every time it is requested.

Step 3: Initialize Koin

The next step is to initialize Koin. You can do this by creating an Application class and adding the following code:

class MyApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger(Level.DEBUG)
androidContext(this@MyApp)
modules(myModule)
}
}
}

In this example, we create an Application class and override the onCreate method. Inside the onCreate method, we initialize Koin by calling startKoin and passing in a logger, the Android context, and our module.

Step 4: Inject dependencies

The final step is to inject your dependencies. You can do this by using the by inject() function in your class:

class MyActivity : AppCompatActivity() {
val myDependency by inject<MyDependency>()
val myFactory by inject<MyFactory>()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

In this example, we inject the dependencies MyDependency and MyFactory into our activity. We can then use these dependencies in our code.

More Examples

In this section you will learn about Koin in Kotlin Android via simple examples.

How to Install Koin

Add the following Gradle dependencies to add Koin to your project:

// Add Maven Central to your repositories if needed
repositories {
mavenCentral()
}

Then declare dependencies as needed:

implementation "io.insert-koin:koin-android:$koin_version"

How to Use Koin

Here is a step by step quickstart tutorial on how to use Koin in Android.

Step 1: Install it

Install it as has been discussed above.

Step 2: Create Components

Create a HelloRepository to provide some data:

interface HelloRepository {
fun giveHello(): String
}

class HelloRepositoryImpl() : HelloRepository {
override fun giveHello() = "Hello Koin"
}

Step 3: Create Presenter

Then create a presenter class, for consuming this data:

class MySimplePresenter(val repo: HelloRepository) {

fun sayHello() = "${repo.giveHello()} from $this"
}

Step 4: Create Koin module

Use the module function to declare a module. Let's declare our first module:

val appModule = module {

// single instance of HelloRepository
single<HelloRepository> { HelloRepositoryImpl() }

// Simple Presenter Factory
factory { MySimplePresenter(get()) }
}

We declare our MySimplePresenter class as factory to have a new instance created each time our Activity need one.

Step 5: 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)
}
}
}

Step 6: Inject Dependencies

The MySimplePresenter component will be created with HelloRepository instance. To get it into our Activity, let's inject it with the by inject() delegate injector:

class MySimpleActivity : AppCompatActivity() {

// Lazy injected MySimplePresenter
val firstPresenter: MySimplePresenter by inject()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

//...
}
}

Download

You can download the code here or read more about Koin here.

Example 1: Kotlin Android Koin and MVP Example

A simple example to get you started with Koin and Model View Presenter in Kotlin Android.

Step 1: Create Project

Start by creating an empty Android Studio project.

Step 2: Dependencies

Add Koin core and Koin-Android as dependencies:

    implementation "org.koin:koin-core:$koinVersion"
implementation "org.koin:koin-android:$koinVersion"

Step 3: Design Layout

Design your MainActivity layout as follows:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.developers.koin.main.MainActivity">

<Button
android:id="@+id/hello_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="15dp"
android:layout_marginStart="15dp"
android:text="@string/show_text"
app:layout_constraintBottom_toTopOf="@+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:text="Hello World!"
android:textColor="@android:color/black"
android:textSize="22sp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Initialize Koin

InitApp.kt

import android.app.Application
import com.developers.koin.main.mainModule
import org.koin.android.ext.android.startKoin

class InitApp : Application() {

override fun onCreate() {
super.onCreate()
startKoin(this, listOf(app, mainModule))
}
}

Step 4: Create Modules

AppModule

import android.app.Application
import org.koin.dsl.module.applicationContext

val app = applicationContext {
provide { Application() }
}

MainModule.kt

import org.koin.dsl.module.applicationContext

val mainModule = applicationContext {
provide { MainPresenter() }
}

Step 5: Create Presenters

MainPresenter.kt

class MainPresenter() {

private var mainView: MainView? = null

fun attachView(mainView: MainView?) {
this.mainView = mainView
}

fun detachView() {
mainView = null
}

fun showMessage() {
mainView?.showMessage("Hello this is Injection from Koin")
}

}

Step 6: Create View

MainView.kt

interface MainView {

fun showMessage(hello: String)

fun showError(error: String)
}

Step 7: Write MainActivity code

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.developers.koin.R
import kotlinx.android.synthetic.main.activity_main.*
import org.koin.android.ext.android.inject

class MainActivity : AppCompatActivity(), MainView {

private val presenter by inject<MainPresenter>()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
presenter.attachView(this)
hello_button.setOnClickListener {
presenter.showMessage()
}
}

override fun showError(error: String) {
//Show Error here
}

override fun showMessage(hello: String) {
textView.visibility = View.VISIBLE
textView.text = hello
}

override fun onDestroy() {
super.onDestroy()
presenter.detachView()
}
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

NumberLink
1.Download Example
2.Follow code author
3.Code: Apache 2.0 License

Conclusion

In this article, we explored how to use Koin in Android. We learned how to add Koin to our project, create a Koin module, initialize Koin, and inject dependencies into our code. Koin is a powerful and easy-to-use dependency injection framework that can help simplify your code and make it easier to manage your dependencies. Give Koin a try and see how it can improve your Android development experience!