Quickstart - Android - Annotations
This tutorial lets you write an Android/Kotlin application and use Koin inject and retrieve your components.
Get the code
Gradle Setup
Add KSP in your root Gradle config:
Add the Koin Android dependency like below:
Our Components
Repository
Let's create a HelloRepository to provide some data:
We tag it with @Single
annotation to declare it as single instance.
Presenter
Let's create a presenter class, for consuming this data:
We tag it with @Factory
annotation, to declare it as Koin factory instance (recreated each time you need)
ViewModel
Let's create a ViewModel class, for consuming this data:
We tag it @KoinViewModel
annotation to declare it as Koin ViewModel instance.
Writing the Koin module
Let's create a AppModule
class to scan our components:
@Module
- tag the class a Module@ComponentScan
- scan given package for Koin definitions
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:
Injecting 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:
The
by inject()
function allows us to retrieve Koin instances, in Android components runtime (Activity, fragment, Service...)
The
get()
function is here to retrieve directly an instance (non lazy)
The MyViewModel
component will be created with HelloRepository
instance. To get it into our Activity, let's inject it with the by viewModel()
delegate injector:
info
The
by viewModel()
function allows us to retrieve a ViewModel instance from Koin, linked to the Android ViewModelFactory.
The
getViewModel()
function is here to retrieve directly an instance (non lazy)