Home > front end >  Pass Application to singleton directly in Android
Pass Application to singleton directly in Android

Time:07-27

I'm a beginner to Android development.

When making a singleton in the Application Context, here is my code.

I pass the application context to the instantiation

class Blah{
 companion object {
        @Volatile
        private var INSTANCE: Blah? = null

        //Singleton
        fun getInstance(applicationContext: Context): Blah =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: Blah(applicationContext).also { INSTANCE = it }
            }
     }
}

Can I pass the application directly to the instantiation? Like so:

class Blah{
 companion object {
        @Volatile
        private var INSTANCE: Blah? = null

        //Singleton
        fun getInstance(application: Application): Blah =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: Blah(application).also { INSTANCE = it }
            }
     }
}

Will this present memory leaks?

CodePudding user response:

Application is also a singleton. This doesn't cause a memory leak because there is only one instance of Application and when your app is running you have one and when your app isn't running there is nothing there, so go for it.

  • Related