In <https://github.com/terrakok/Compose-Multiplatf...
# multiplatform
a
In https://github.com/terrakok/Compose-Multiplatform-Wizard why is it creating the
AndroidApp
class is implemented as a singleton!? 🤔
x
The
AndroidApp
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 startup
a
Yes
Exactly
Not a singleton per se yeah, wrong description
Copy code
class AndroidApp : Application() {
    companion object {
        lateinit var INSTANCE: AndroidApp
    }

    override fun onCreate() {
        super.onCreate()
        INSTANCE = this
    }
}
Why such behavior?
1
c
The
Application
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 casts
❤️ 2
x
I was pretty much going to say the same as @Casey Brooks. The
Application
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 cases
a
Thanks!
a
I believe it's still not recommended to store Application context into a global variable. 1. It may break features like Instant Run/Live Edit 2. If the process is killed and a ContentProvider is called, the application may be still
null
.
👆🏾 1
👆 4
❤️ 4
There should also be a lint warning about it. At least it was in Java, as far as I remember.
x
I was unaware of what you’re saying here @Arkadii Ivanov. Thanks for the info!
👍 1
e
I think it is “dirty” example for simplest dependency container
1