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()
}