https://kotlinlang.org logo
#android
Title
# android
l

luke_c

10/11/2018, 12:19 PM
Is the application context only garbage collected when the application is destroyed, or is there any other scenarios where it might happen? Trying to understand why when creating singletons / kotlin objects it seems normal to pass in the context every time. Could you not just initialise it with the context one then call getInstance() or whatever without having to pass in the context? The object would be initialised in the Application class of course
e

Egor Trutenko

10/11/2018, 12:24 PM
Most likely it happens to avoid implicit state and keep context-dependent components within scope of context holders, e.g. activity, view, fragment etc. So, if you push application instance into object it is what they call "code smell", because every time you do it you have to deal with the fact that now this component is implicitly dependent on Android Framework dependencies and it becomes way harder to extract reusability from such component.
s

Sam

10/11/2018, 1:59 PM
On a side note, Application object once created stays alive and follows process lifecycle. It says alive even on an empty process (without any android components). This is why there isn't any onDestroy in it.
3 Views