Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Fragment's argument item to Koin dependency graph?

I have a ViewModel which has a dependency which should be taken from the Fragment's arguments.

So its something like:

class SomeViewModel(someValue: SomeValue)

now the fragment recieves the SomeValue in its arguemnt like so:

class SomeFragment : Fragment() {
    val someViewModel: SomeViewModel by viewModel()

    companion object {
        fun newInstance(someValue: SomeValue) = SomeFragment().apply {
            arguments = bundleof("someKey" to someValue)
        }
    }
}

problem is I don't know how to add SomeValue thats taken from the Fragment's arguments to Koin's module.

Is there a way to make the fragment contribute to the Koin Dependency Graph?

like image 847
Archie G. Quiñones Avatar asked Jun 04 '19 02:06

Archie G. Quiñones


People also ask

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 startKoin?

The startKoin function​ The startKoin function is the main entry point to launch Koin container. It need a list of Koin modules to run. Modules are loaded and definitions are ready to be resolved by the Koin container.

How Koin works Android?

Implementation of a Koin Module As the name implies, a module is created using the module function. Creating a singleton instance requires the keyword single. This indicates that when the dependency is required, Koin will return the same instance of the class.

What is KOIN container?

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.


Video Answer


1 Answers

So for anyone else asking the same question, here is the answer:

https://doc.insert-koin.io/#/koin-core/injection-parameters

So basically,

you could create your module like so:

val myModule = module {
    viewModel { (someValue : SomeValue) -> SomeViewModel(someValue ) }
}

Now in your fragment, you could do something like:

class SomeFragment : Fragment() {
    val someViewModel: SomeViewModel by viewModel { 
        parametersOf(argument!!.getParcelable<SomeValue>("someKey")) 
    }

    companion object {
        fun newInstance(someValue: SomeValue) = SomeFragment().apply {
            arguments = bundleof("someKey" to someValue)
        }
    }
}
like image 180
Archie G. Quiñones Avatar answered Sep 21 '22 16:09

Archie G. Quiñones