Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Koin how to inject outside of Android activity / appcompatactivity

Koin is a new, lightweight library for DI and can be used in Android as well as in standalone kotlin apps.

Usually you inject dependencies like this:

class SplashScreenActivity : Activity() {      val sampleClass : SampleClass by inject()      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)     } } 

with the inject() method.

But what about injecting stuff in places where Activity context is not available i.e. outside of an Activity?

like image 551
kosiara - Bartosz Kosarzycki Avatar asked Apr 03 '18 11:04

kosiara - Bartosz Kosarzycki


People also ask

How do you inject ViewModel in KOIN?

To inject a state ViewModel in a Activity , Fragment use: by viewModel() - lazy delegate property to inject state ViewModel instance into a property. getViewModel() - directly get the state ViewModel instance.

Does KOIN use reflection?

Koin works without any use of proxies, code generation or reflection. This makes it as usable in Android Apps and Ktor Microservices as standard Java programs.

What is KoinComponent?

For example, if you need to get some dependencies in your repository then you can simply implement the KoinComponent interface. It gives you access to various Koin features such as get() and inject() . Use KoinComponent only when you can't rewrite the constructor to accept dependencies as constructor parameters.


2 Answers

There is the KoinComponent which comes to the rescue. In any class you can simply:

class SampleClass : KoinComponent {      val a : A? by inject()     val b : B? by inject() } 

Extending KoinComponent gives you access to inject() method.

Remember that usually it's enough to inject stuff the usual way:

class SampleClass(val a : A?, val b: B?) 
like image 152
kosiara - Bartosz Kosarzycki Avatar answered Sep 20 '22 10:09

kosiara - Bartosz Kosarzycki


Koin provides a solution for this using the KoinComponent interface. For example, if you need to get some dependencies in your repository then you can simply implement the KoinComponent interface. It gives you access to various Koin features such as get() and inject(). Use KoinComponent only when you can't rewrite the constructor to accept dependencies as constructor parameters.

class MyRepository: Repository(), KoinComponent {   private val myService by inject<MyService>() } 

Constructor injection is better than this approach.

For example, the same thing can be achieved by:

class MyRepository(private val service: MyService): Repository() {     ... } 

And you can add the definition for instantiating this class in a koin module:

val serviceModule = module {     ...      factory { MyService() } } val repositoryModule = module {     ...      factory { MyRepository(get<MyService>()) } } 
like image 41
harold_admin Avatar answered Sep 19 '22 10:09

harold_admin