https://kotlinlang.org logo
#android
Title
# android
k

Katie Levy

06/07/2018, 6:28 PM
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

louiscad

06/07/2018, 9:41 PM
I'll add that Kotlin Coroutines allows for easy cancellation, even with highly asynchronous code, which is good at avoiding memory leaks
r

radityagumay

06/08/2018, 2:56 AM
You should set the reference null in appropriate callback.
@louiscad how did you wrapped inner classes with couroutine?
l

louiscad

06/08/2018, 5:46 AM
@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

radityagumay

06/08/2018, 6:05 AM
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

louiscad

06/08/2018, 9:35 AM
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

louiscad

06/24/2018, 3:27 PM
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

radityagumay

06/27/2018, 5:41 AM
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
28 Views