How does Kotlin handle for memory leaks running on...
# android
k
How does Kotlin handle for memory leaks running on the assumption that null is bad. In the case of listeners and inner classes, don't we need to remove the reference to them by setting them to null to allow for garbage collection and avoid memory leaks?
l
I'll add that Kotlin Coroutines allows for easy cancellation, even with highly asynchronous code, which is good at avoiding memory leaks
r
You should set the reference null in appropriate callback.
@louiscad how did you wrapped inner classes with couroutine?
l
@radityagumay I don't set references to null because I don't reference them in references that are longer lived than where they belong to (ViewModel, JobService/Worker, Fragment or Activity)
r
In @Katie Levy case, I believe she put the listener reference in view. So, in that case you should set it as null in appropriate callback
l
There's no problem in putting a listener in a view and not removing it. The problem can be the other way around, having a reference to your view (or something tied to it like a Fragment or an Activity) that lives longer than the View/Activity/Fragment itself.
@louiscad
l
It's true that my statement was inexact, you can have a leak by giving a reference through a listener registration and not removing it. However, there's no problem in case of something UI related like a
View.OnClickListener
since they all have the same scope/lifecycle and will get garbage collected together.
r
Yes, that valid for
View.OnClickListener
. But not for EditText.addTextChangedListener(TextWatcher), they have function
removeTextChangedListener
to remove that listener. for simple OnClickListener we didnt remove it. but, there are a cases android view listener should removed @louiscad
@Katie Levy better you read lapsed listener problem