Hey! Can somebody tell me if injecting a Singleton...
# compose
m
Hey! Can somebody tell me if injecting a Singleton via
koinInject()
inside a Composable is expensive? Let’s say I have a
LazyList
with 100 elements. Each list item is a Composable. Should I pass an instance of my needed Singleton to the Composable, or is it no overhead to lookup the Singleon via
koinInject()
inside the list item Composable?
s
You can look at what koinInject does internally. I can't answer performance wise, but code structure wise I'd prefer not to do this as opposed to just passing down the thing you want to down the tree normally.
f
If you are creating modules by single you can use
koinInject
. But if its factory you should rather pass it
l
I would not recommend doing so. Apart from the potential performance issue, it makes your composable un-reviewable and un-screenshot-testable.
f
In that case i can always mock dependencies. For performance: koinInject provides objects from cache pool for singleton instance its also backed up by compose remember.
l
How can you mock dependencies in a Preview function? Maybe you could however as you have more and more this usages meaning more implicit dependencies you'll get in your composable which make it harder to switch DI tools or refactor IMO. Passing dependencies down seems better to me.
plus1 1
m
@Stylianos Gakis It internally uses
remember
and performs a lookup of the requested instance. The lookup seems like a bit overhead to me. I agree with all the comments, I should refactor my code and pass all instances down, also for Previews 👍