will Passing Android activity to a dependency ( a variable in the same class ) cause Memory Leaks

27 views Asked by At

I have code like this.

Class MyActivity {
private lateinit var downLoadQRHandler: DownloadQRHandler
...
fun someFun()

{     val model = getDataModelSomeOtherFun()
 downLoadQRHandler = DownloadQRHandler(downloadQRModel, this)
}
}

As the activity is passed to one of the dependencies?

Will it cause Memory Leaks? At first I though, yes it would. BUt I think, after activity getting destroyed this reference downLoadQRHandler will automatically nullify. And MyActivity instance will be garbage collected.

to be on the safe side, I though of adding this in onDestroy()

  override fun onDestroy() {
        super.onDestroy()
        downLoadQRHandler = null
}

Does it have any benefit of adding the ..= null code?

The activity class was flagged in the memoryProfiler and leakCanary. There could be other reasons for the memory leaks.

1

There are 1 answers

1
emandt On

Without see other piece of code it's not possible to answer you. If "downLoadQRHandler" is used elsewhere and retained in memory, yes it could be a memory leak especially if DownloadQRHandler() constructor (which accepts an Activity) holds the Activity for later use.