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
Stylianos Gakis
06/23/2024, 11:17 AM
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
Farhazul Mullick
06/24/2024, 4:13 AM
If you are creating modules by single you can use
koinInject
. But if its factory you should rather pass it
l
lesincs
06/24/2024, 5:18 AM
I would not recommend doing so. Apart from the potential performance issue, it makes your composable un-reviewable and un-screenshot-testable.
f
Farhazul Mullick
06/24/2024, 5:33 AM
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
lesincs
06/24/2024, 5:40 AM
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
Max
06/24/2024, 3:56 PM
@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 👍