Hi all, I'm feeling I make something weird / dumb ...
# koin
d
Hi all, I'm feeling I make something weird / dumb with Koin, so I thought I should ask how you would solve the problem. Imagine you have an Android
Activity
that gets some parameters via an
Intent
. That activity is the host of multiple different compose screens, all requiring parts of these parameters. What I now want to achieve is something similar to the ease how
SavedStateHandle
provided access to
Fragment
arguments in the old days, basically if you had a
Bundle().apply { putInt("foo", 1) }
set as argument, you could simply inject
SavedStateHandle
in your
ViewModel
and asked it for a key
foo
to receive the expected value. By re-creating that same "experience" with Koin and my example intent data I did the following: • Let my
Activity
implement
AndroidScopeComponent
and retrieve my scope via
by activityRetainedScope()
• Use
scope.declare(myData)
to make my (parsed)
Intent
data available in this scope • Wrap my root composable into a custom composition local provider:
CompositionLocalProvider(LocalKoinScopeContext provides ComposeContextWrapper(scope) { scope }) { ... }
• Define my ViewModels inside the retained scope, like so:
module { activityRetainedScope { viewModelOf(::ViewModelClass) }}
Now
MyData
can be injected in
ViewModelClass
, but this all looks very awkward. I was originally thinking that I should be able to somehow "link" the two different scopes, the activity-retained scope from the Activity to the individual ViewModel scopes for the different screens, but since the activity-retained scope is tied to a custom viewmodel underneath this has no "visibility" to the other VMs and vice versa. So, how would you solve this? And also, would it help anyhow to have this new
Copy code
options(
    viewModelScopeFactory()
)
in place? Thanks in advance!
👀 1
s
Wouldn't it be better to pass parameters when injecting VM? Something like
Copy code
val viewModel by viewModel<ViewModelClass>(parameters = { parametersOf(myData) })

MyData still can be provided via composition local
Also prefer passing only what this particular ViewModel needs (perhaps only some parts of
MyData
) This way you don't need to deal with scope linking and such because it's unnecessary Also
Copy code
options(
    viewModelScopeFactory()
)
Won't help here, because you won't have access to this scope, so you won't be able to
declare
anything upon its creation
a
@dead.fish your approach is perhaps overcomplex. I would try first to propagate via parameter injection as mentioned by Sergey. The use of
viewModel<ViewModelClass>(parameters = { parametersOf(myData) })
will allow you to pass this value to your
ViewModelClass
. Else you need to setup/size your scopes for it.
viewModelScopeFactory
open scope at ViewModel creation, you won't have the hand on it, outside of the scope.
👍 1