humblehacker
11/30/2022, 2:34 AMfactory { Service() }, and I'm attempting to use it in a class as a property declared as val service: Service by inject(). It works, but it seems that every time I reference that property in my class, Koin creates a new instance. Is that how it's supposed to work? I expected it to construct the Service lazily, but after that I'd get the same instance until the parent class is destroyed. Changing by inject() to = get() gets me the behavior I want, but I really want to know why by inject() isn't working as I expect.Sebastian Schuberth
11/30/2022, 8:16 AMfactory {}. If you don't want a new instance to be created on each injection, use single {} instead.humblehacker
11/30/2022, 4:23 PM= get() but not with by inject(). It seems quite odd that every time I reference a property declared by inject(), the old instance is released and a new one created.
single {} would give me the same instance every time I create a new instance of the parent class, which is not what I want.Sebastian Schuberth
11/30/2022, 4:26 PMhumblehacker
11/30/2022, 6:14 PMby inject() under the hood uses Lazy with LazyThreadSafeMode.NONE as default (unlike by lazy() which defaults to LazyThreadSafeMode.SYNCHRONIZED), and since I was accessing my property from multiple threads (via suspendCancellableCoroutine), multiple instances were created before Lazy had a chance to store one.
Solution is to change my property declaration like so:
val service: Service by inject(mode = LazyThreadSafetyMode.SYNCHRONIZED)
or take other steps to ensure thread-safe access to that property.