Android & Annotations
This tutorial lets you write an Android application and use Koin dependency injection to retrieve your components. You need around 10 min to do the tutorial.
update - 2024-10-21
Get the code
Gradle Setup
Let's configure the KSP Plugin like this, and the following dependencies:
plugins {
alias(libs.plugins.ksp)
}
dependencies {
// ...
implementation(libs.koin.annotations)
ksp(libs.koin.ksp)
}
// Compile time check
ksp {
arg("KOIN_CONFIG_CHECK","true")
}
See libs.versions.toml for current versions
Application Overview
The idea of the application is to manage a list of users, and display it in our MainActivity class with a Presenter or a ViewModel:
Users -> UserRepository -> UserService -> (Presenter or ViewModel) -> MainActivity
The "User" Data
We will manage a collection of Users. Here is the data class:
data class User(val name: String, val email: String)
We create a "Repository" component to manage the list of users (add users or find one by name). Here below, the UserRepository interface and its implementation:
interface UserRepository {
fun findUserOrNull(name: String): User?
fun addUsers(users: List<User>)
}
@Single
class UserRepositoryImpl : UserRepository {
private val _users = arrayListOf<User>()
override fun findUserOrNull(name: String): User? {
return _users.firstOrNull { it.name == name }
}
override fun addUsers(users: List<User>) {
_users.addAll(users)
}
}
The UserService Component
Let's write a service component to manage user operations:
interface UserService {
fun getUserOrNull(name: String): User?
fun loadUsers()
fun prepareHelloMessage(user: User?): String
}
@Single
class UserServiceImpl(
private val userRepository: UserRepository
) : UserService {
init {
loadUsers()
}
override fun getUserOrNull(name: String): User? = userRepository.findUserOrNull(name)
override fun loadUsers() {
userRepository.addUsers(listOf(
User("Alice", "alice@example.com"),
User("Bob", "bob@example.com"),
User("Charlie", "charlie@example.com")
))
}
override fun prepareHelloMessage(user: User?): String {
return user?.let { "Hello '${user.name}' (${user.email})! 👋" } ?: "❌ User not found"
}
}
The Koin module
Let's declare a AppModule module class like below:
@Module
@ComponentScan("org.koin.sample")
@Configuration
class AppModule
@Module- Declares this class as a Koin module@ComponentScan("org.koin.sample")- Automatically scans and registers all Koin definitions in the"org.koin.sample"package@Configuration- Enables automatic module discovery when used with@KoinApplication
With component scanning enabled, we simply add annotations to our classes:
@Single
class UserRepositoryImpl : UserRepository {
// ...
}
@Single
class UserServiceImpl(private val userRepository: UserRepository) : UserService {
// ...
}
The @Single annotation declares these classes as singletons in Koin.
Displaying User with Presenter
Let's write a presenter component to display a user:
@Factory
class UserPresenter(private val userService: UserService) {
fun sayHello(name: String): String {
val user = userService.getUserOrNull(name)
val message = userService.prepareHelloMessage(user)
return "[UserPresenter] $message"
}
}
UserService is referenced in UserPresenter's constructor
We declare UserPresenter with the @Factory annotation, to create a new instance each time it's requested (avoids memory leaks with Android lifecycle):
@Factory
class UserPresenter(private val userService: UserService) {
// ...
}
Injecting Dependencies in Android
The UserPresenter component will be created, resolving the UserService instance with it. To get it into our Activity, let's inject it with the by inject() delegate function:
class MainActivity : AppCompatActivity() {
private val presenter: UserPresenter by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//...
}
}
That's it, your app is ready.
The by inject() function allows us to retrieve Koin instances, in Android components runtime (Activity, fragment, Service...)
Start Koin
We need to start Koin with our Android application. With the @KoinApplication annotation, Koin automatically discovers and loads all modules marked with @Configuration:
import org.koin.android.ext.koin.androidContext
import org.koin.core.annotation.KoinApplication
import org.koin.ksp.generated.*
@KoinApplication
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MainApplication)
}
}
}
Key Points:
@KoinApplication- Automatically discovers all modules annotated with@Moduleand@Configuration- No need to manually call
modules(AppModule().module)- modules are loaded automatically! - The
import org.koin.ksp.generated.*import is required for generated Koin content - You only need to configure Android-specific settings like
androidContext
The @KoinApplication annotation works with @Configuration on your module to automatically discover and load all dependencies at compile time via KSP.
Displaying User with ViewModel
Let's write a ViewModel component to display a user:
@KoinViewModel
class UserViewModel(private val userService: UserService) : ViewModel() {
fun sayHello(name: String): String {
val user = userService.getUserOrNull(name)
val message = userService.prepareHelloMessage(user)
return "[UserViewModel] $message"
}
}
UserService is referenced in UserViewModel's constructor
The UserViewModel is tagged with @KoinViewModel annotation to declare the Koin ViewModel definition. This ensures proper lifecycle management and avoids memory leaks.
Injecting ViewModel in Android
The UserViewModel component will be created, resolving the UserService instance with it. To get it into our Activity, let's inject it with the by viewModel() delegate function:
class MainActivity : AppCompatActivity() {
private val viewModel: UserViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//...
}
}
Compile Time Checks
Koin Annotations allows to check your Koin configuration at compile time. This is available by jusing the following Gradle option:
ksp {
arg("KOIN_CONFIG_CHECK","true")
}