Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

467
Visualizações
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()

}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

When you call the getInstance() for the first time, the Context that you pass to this function is saved forever. So, the context in further getInstance() calls doesn't have anything to do there. I never save this Context.

This is what I am doing:

Create an object in Kotlin and initialize the object with a context as soon as the app starts. Instead of storing the context, I perform whichever operation is required with that context.

object PreferenceHelper {

    private var prefs: SharedPreferences? = null

    fun initWith(context: Context){
        if(prefs == null) this.prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE)
    }

    fun someAction(){ .... }
}

and inside the Application class:

class MyApp: Application(){
   override fun onCreate(){
      PreferenceHelper.initWith(this)
   }
 }

and later anywhere in the app:

 PreferenceHelper.someAction()

You can do this if you don't need a reference to the Context every time you perform something with the Singleton class.

over 4 years ago · Santiago Trujillo Relatório

0

I would not store the context in the SingletonClass, I would simply pass the context to each method of the class via dependency injection. Something like:

SingletonClass.callMethod(context)

Define the "static" method in the companion object like that:

 companion object {
        fun callMethod(context: Context) {
            // do Something
        }
    }

Then call it from your activity with:

SingletonClass.callMethod(this)

Hope that it helps :)

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda