Using lifecycle-viewmodel-ktx
and lifecycle-livedata-ktx
and given the following example:
ViewModel implementation:
class AutocompletionViewModel: ViewModel() {
fun getAutocompletion(inputString: CharSequence?) = liveData {
delay(10)
emit("$inputString DUMMY AUTOCOMPLETION")
}
}
Fragment part:
val viewModel by viewModels<AutocompletionViewModel>()
/* Acquiring EditText*/
editText.addTextChangedListener(object: TextWatcher{
override fun afterTextChanged(editable: Editable?) {
viewModel.getAutocompletion(editable).observe(viewLifecycleOwner, Observer { editable?.append(it) })
}
/* Other TextWatcher method implementations*/
})
Would this code cause a memory leak if the user types text into the EditText?
I assume that with every text change a new LiveData
object with a stong referenced Observer
is created (and will be alive until the fragment is destroyed). Nevertheless, a similar example was shown by the official docs: https://developer.android.com/topic/libraries/architecture/coroutines#livedata
Yes, there is memory leak:
I attached Android Studios memory profiler and executed AutocompletionViewModel.getAutocompletion
10 thousand times. Regardless of a garbage collection, Observer
and LiveData
objects remain still in memory:
Conclusion for this case: LiveData
object should be backed by a property and Observers
should only be attached once