具有上下文的无内存泄漏的Singleton [英] Memory-leak free Singleton with context
问题描述
我正在尝试实现以下单例模式:SingletonClass.getInstance(context).callMethod()
I am trying to implement the following singleton pattern: SingletonClass.getInstance(context).callMethod()
尽管有各种各样的教程说明了如何在Kotlin中制作单身人士,但都没有一个关于在静态字段中持有context
会导致Android内存泄漏的事实.
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?
更新:
这是我对CommonsWare解决方案2的实现.我用过Koin.
Here is my implementation of CommonsWare's solution #2. I used Koin.
单班:
class NetworkUtils(val context: Context) {
}
应用程序类:
class MyApplication : Application() {
val appModule = module {
single { NetworkUtils(androidContext()) }
}
override fun onCreate() {
super.onCreate()
startKoin(this, listOf(appModule))
}
}
活动分类:
class MainActivity : AppCompatActivity() {
val networkUtils : NetworkUtils by inject()
}
推荐答案
选项1:让getInstance(Context)
调用提供的Context
上的applicationContext
并保持该状态. Application
单例是在您的过程在该过程中使用的,并且在该过程中有效.它是预先泄漏的;您不能再泄漏它了.
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.
选项2:摆脱getInstance()
并设置某种形式的依赖项注入(Dagger 2,Koin等).这些DI框架有一些方法可以使它们为创建并注入到下游的单例提供Application
单例.
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.
这篇关于具有上下文的无内存泄漏的Singleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!