Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the usage of livedata-ktx with ViewModels causing memory leaks if the LiveData is not backed by a property?

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

like image 290
user1185087 Avatar asked Jan 24 '26 12:01

user1185087


1 Answers

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: enter image description here

Conclusion for this case: LiveData object should be backed by a property and Observers should only be attached once

like image 192
user1185087 Avatar answered Jan 27 '26 01:01

user1185087



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!