I am trying to implement the following singleton pattern: SingletonClass.getInstance(context).callMethod()
While there are a variety of tutorials that explain how to make singletons in Kotlin, none of them address the fact that holding a context
in a static field will cause memory leaks in Android.
How do I create the above pattern without creating a memory leak?
Update:
Here is my implementation of CommonsWare's solution #2. I used Koin.
Singleton class:
class NetworkUtils(val context: Context) {
}
Application Class:
class MyApplication : Application() {
val appModule = module {
single { NetworkUtils(androidContext()) }
}
override fun onCreate() {
super.onCreate()
startKoin(this, listOf(appModule))
}
}
Activity class:
class MainActivity : AppCompatActivity() {
val networkUtils : NetworkUtils by inject()
}
Option #1: Have getInstance(Context)
call applicationContext
on the supplied Context
and hold that. The Application
singleton is created when your process is and lives for the life of the process. It is pre-leaked; you cannot leak it further.
Option #2: Get rid of getInstance()
and set up some form of dependency injection (Dagger 2, Koin, etc.). There are recipes for these DI frameworks to have them supply the Application
singleton to the singletons that they create and inject downstream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With