I have been having some weird issues in my Android app when closing it via back key and reentering, and found they are happening because variables in 2 Singleton classes I have are never re-initializing (The issue doesn't happen if manually killing the app from task manager).
Even after I call finish explicitly on Main activity onBackPressed and I can see onDestroy is called, the Singletons are still in memory.
I decided to do manual cleanup of these Singletons before destroying my Activity, the problem is using Kotlin I would need to make all their member variables nullable (?) and it would be a lot of hassle to remember to assign null to every variable, so for now I opted to handle the instantiation of the Singleton like this and just make null the whole instance while cleaning:
class SingletonName {
companion object {
private var _instance: SingletonName ? = null
private var instance: SingletonName ?
get() {
if (_instance == null) {
_instance = SingletonName ()
}
return _instance
}
set(value) {
_instance = value
}
@JvmStatic fun get(): SingletonName {
return instance!! //avoid having to deal with nullable value in client code
}
}
//need to make sure to call this before destroying main activity
fun cleanup() {
instance = null
}
}
Client use:
SingletonName.get().somefunc()
These seems more involved than it should, and I know this is not even thread safe, but keep in mind that simply using the 'object' keyword instead of 'class' will not work, as it will prevent any initialization taking place the second time I run the app (the constructor is not being called again and I can't force destroy the instance).
This makes me think it might be worth looking into Android dependency injection but I feel like at least one of my Singletons really needs to be accessed on a lot of places so it might not be an elegant solution either (Probably need to refactor it into smaller functionalities).
The main issue here is the way android handles destruction but I guess I can't change that, I don't see any reason why it keeps all the static values of non activity classes if the application activities are already destroyed.
The question is how do you deal with this cases regardless of the language used? or what do you think are the best practices in this case?
Edit: Actually I just did a test with Dagger 2, and the same problem happens, if I use @Provides and @Singleton, the values of member variables on the provided object the second time launching the app are not null so I guess this needs to be dealt with explicitly unless I am missing some more annotations to tell Dagger that the instance should be released at the end of the app life-cycle.