Hi everyone :wave: How does the Android DI library...
# android
m
Hi everyone šŸ‘‹ How does the Android DI library hold singleton objects? For example, Dagger, Koin, etc. are stored internally just by passing Context. I want to know the internal processing. We also to be aware garbage collection šŸ˜¢
stackoverflow 5
šŸ‘€ 1
j
Dagger knows nothing about Context. Singleton in Dagger just means initialize once and return the same instance. You still need to keep the component instance around for as long as you want the singletons to live.
šŸ‘ 1
a
In Koin
single
is created upon request and returned same instance for every futher requests. But in Koin you can make
single
instance inside particular scope, not only until the app is killed. It is much easier to keep instances unless you are in the particular scope of the app and close the scope once you don't need it. In worst case you can call
close
on koin instance and it will release all the resources from existing
koin
context.
a
Dagger 2 has annotation
@Scope
as a mechanism to handle scoping. Scoping allows you to ā€œpreserveā€ the object instance and provide it as a ā€œlocal singletonā€ for the duration of the scoped component. Annotation
@Singleton
is just another scope. It was just there as the default scoping annotation. It provides your dependencies as a singleton as long as you are using the same component.
m
If the following is defined, will the instance be destroyed?ļ¼ˆBecause of GCļ¼‰
Copy code
object SampleObject {
Ā Ā val instance = SampleClass()
}
To solve that problemā†“
Copy code
class SampleApplication: Application {
Ā Ā val instance = SampleClass()
Ā Ā ā€¦.
}
But Koin doesn't keep instances in application classes. Is the singleton classes of Koin destroyed by GC?
a
Object is the same static object at the end of all and as any other static objects it will be there. Of cause if put an instance into
Application
class it would be more safe. But it is again the matter of a need. Application could stay in the memory also for a long time. With koin, you can call
stopKoin()
at any time or reload the module/modules and it will clear all the instances of the classes or scoped instances could be used.
šŸ‘ 1
m
thanks for your reply. Your advice was helpful. If a singleton is used on the library side in an application composed of multiple modules, is it better to have a singleton instance in "object"?
a
object
should be something that could not lock anything and that is not heavy. I'm using object classes only for easy access for grouped static functions. Not sure if there are some other use cases, but other than that I would prefer some scope for an object. And if there is no scope and object is not big, I could use single instance from DI(koin) over
object
because I can replace it for tests for example. While
object
you can't replace.
šŸ‘ 1
m
Thank you for your kindness!