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?
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.
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.
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.
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.
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)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With