19

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?

pRaNaY
  • 24,642
  • 24
  • 96
  • 146
Archie G. Quiñones
  • 11,638
  • 18
  • 65
  • 107

1 Answers1

38

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)
        }
    }
}
SnyersK
  • 1,296
  • 8
  • 23
Archie G. Quiñones
  • 11,638
  • 18
  • 65
  • 107
  • 3
    New URL: https://doc.insert-koin.io/#/koin-core/injection-parameters – Big McLargeHuge Mar 01 '20 at 18:00
  • Thanks a ton!!! Do you happen to know if (for the scenario above) `parametersOf(this)` can be used? I do not understand this construct. Is it mapping by name or should I call some setParameter before I'm using view model? – ror Apr 02 '20 at 17:18
  • can you clarify your question more so I could answer it better?? – Archie G. Quiñones Apr 03 '20 at 05:45
  • But what will it look like if the viewModel also receives single dependencies, such as repository? – Leo DroidCoder Dec 30 '20 at 07:45
  • 8
    Even newer URL https://insert-koin.io/docs/reference/koin-android/viewmodel#viewmodel-and-injection-parameters – Igor Feb 14 '21 at 08:40