Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory-leak free Singleton with context

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

}
like image 718
Roymunson Avatar asked Jan 28 '19 19:01

Roymunson


1 Answers

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.

like image 137
CommonsWare Avatar answered Sep 18 '22 18:09

CommonsWare