Hi everybody, I am trying to find a good solution ...
# koin
v
Hi everybody, I am trying to find a good solution for a following use case without overengineering it: I have generic stuff, that is currently sitting in the root scope. I also have user session-related stuff, which is currently in
SCOPE_USER
. This scope is created when user logs in and I close it on logout. There is a custom
by injectUser()
function to inject things from this scope for convenience. Question: is it possible to link
SCOPE_USER
to root when it is created and close it when user logs out? Or should I rather create another
SCOPE_GENERAL
for all the stuff, that is currently in root and then link
SCOPE_USER
to it? This would require to inject from a scope -> custom
by injectGeneric()
function. Ideally linking stuff to root scope would be ideal, but I do no see a way to do it. Or should I rather keep things as they are? Many thanks for any ideas in advance!
a
by default a scope fallback to the root scope
if a definition is not in your scope, we look at the root scope
you could have your
injectUser()
with something like:
fun injectUser() = getKoin().getOrCreateScope(SCOPE_USER).get<User>()
v
yes, thanks, this is more or less how it is done now. And I have read about scopes falling back to root scope as well. I was wondering if I can when creating a scope link it to the root one, so I can just use default
by inject()
and
by viewModel()
methods. I have mixed feelings about this approach, but part of me feels it would be simpler this way. It kind of reverses the notion of scopes falling back to root and makes the root one “be aware” (after linking) about scoped things though. some context: DI graph is not crazy large, so there is no performance implications, at least not currently. Scope is more to keep all the session-related moments in one bucket and wipe them altogether when user logs out to avoid leaking anything to the next user
a
you can use directly your scope to inject instances from it
scope.get()
,
scope.inject()
or
scope.getViewModel()
. The thing is to retrieve it where you need it
v
thanks!