aj
08/01/2023, 3:33 PMAndroidApp
class is implemented as a singleton!? 🤔xoangon
08/01/2023, 3:39 PMAndroidApp
is not created as a singleton, as it is not even created manually. It’s only holding an static reference to the app instance created on the app startupaj
08/01/2023, 3:40 PMaj
08/01/2023, 3:40 PMaj
08/01/2023, 3:41 PMaj
08/01/2023, 3:41 PMclass AndroidApp : Application() {
companion object {
lateinit var INSTANCE: AndroidApp
}
override fun onCreate() {
super.onCreate()
INSTANCE = this
}
}
aj
08/01/2023, 3:41 PMCasey Brooks
08/01/2023, 3:41 PMApplication
class is always a singleton, because that’s how the Android framework creates and handles it. The generator is not creating the singleton, it’s just assigning the instance to a variable to make it easy to access throughout the rest of the app. This is a very common pattern among Android apps (though it’s arguable whether or not it is a good or necessary pattern in pure compose apps)
The alternative would be something like context.applicationContext as AndroidApp
, littering your app with unchecked castsxoangon
08/01/2023, 3:43 PMApplication
instance won’t be garbage collected as it’s always used. So there’s no penalty on having it as an static reference, and it’s pretty handy for some use casesaj
08/01/2023, 3:46 PMArkadii Ivanov
08/01/2023, 3:48 PMnull
.Arkadii Ivanov
08/01/2023, 3:49 PMxoangon
08/01/2023, 3:49 PMEugen Martynov
08/01/2023, 3:54 PM