Koin Components

Koin Components

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

class MyService {}
// Define a singleton for MyService
var myModule = module()..single((s) => MyService());

we start Koin before using definition.

Start Koin with myModule

void main(vararg args : String){
// Start Koin
startKoin((app){
app.module(myModule);
});
// Create MyComponent instance and inject from Koin container
MyComponent();
}

Here is how we can write our MyComponent to retrieve instances from Koin container.

Use get() & by inject() to inject MyService instance.

class MyComponent extends View with KoinComponentMixin {
MyService myService;
Lazy<MyService> myServiceLazy;
MyComponent() {
// lazy inject Koin instance
myServiceLazy = inject<MyService>();
// or
// eager inject Koin instance
myService = get<MyService>();
}
}

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
// is lazy evaluated
Lazy<MyService> myService = inject();
// retrieve directly the instance
MyService myService = get();
note

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 get() or by inject()

  • qualifier - name of the definition (when specified name parameter in your definition)

Example of module using definitions names:

class ComponentA {}
class ComponentB {
final ComponentA componentA;
ComponentB(this.componentA);
}
final myModule = module()
..single((s) => ComponentA(), qualifier: named("A"))
..single((s) => ComponentB(s.get()), qualifier: named("B"));

We can make the following resolutions:

// retrieve from given module
var a = get<ComponentA>(named("A"))

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 KoinComponent interface.