Koin is a DSL to help describe your modules & definitions, a container to make definition resolution. What we need now is an API to retrieve our instances outside of the container. That's the goal of Koin components.
Create a Koin Component
To give a class the capacity to use Koin features, we need to tag it with
KoinComponent interface. Let's take an example.
A module to define MyService instance
we start Koin before using definition.
Start Koin with myModule
Here is how we can write our
MyComponent to retrieve instances from Koin container.
get() & by
inject() to inject MyService instance.
Unlock the Koin API with KoinComponent
Once you have tagged your class as
KoinComponent, you gain access to:
inject()- lazy evaluated instance from Koin container
get()- eager fetch instance from Koin container
Retrieving definitions with get & inject
Koin offers two ways of retrieving instances from the Koin container:
Lazy<T> t = inject<T>()- lazy evaluated delegated instance
T t = get<T>()- eager access for instance
The lazy inject form is better to define property that need lazy evaluation.
Resolving instance from its name
If you need you can specify the following parameter with
qualifier- name of the definition (when specified name parameter in your definition)
Example of module using definitions names:
We can make the following resolutions:
No inject() or get() in your API?
If your are using an API and want to use Koin inside it, just tag the desired class with