Search code examples
androidkotlindata-bindingandroid-databinding

Is it okay to pass views into AndroidViewModel


I know passing views to ViewModel classes causes memory leaks but will it also cause memory leaks if I pass a view, let's say, a ProgressBar, in to an AndroidViewModel class like the following?

class MainActivityViewModel (application: Application, progressBar: ProgressBar): AndroidViewModel(application) {
    var name: LiveData<String> = Transformations.map(docRef) {
        progressBar.visibility = View.GONE
        it.getString("string")
    }
}

I'm going to be using Data Binding to call name from my layout file like android:text="@{viewModel.name]".

Will the above code cause a memory leak?


Solution

  • Will the above code cause a memory leak?

    Yes, if the device undergoes a configuration change, such as the user rotating the screen.

    In that case, your activity and its views will be destroyed and recreated, but your MainActivityViewModel will be retained and given to the new activity instance. But, it will still be holding a reference to progressBar from the old activity. This means:

    • Android cannot garbage-collect the old activity, since your viewmodel is holding a reference to a View from that activity

    • Calls to progressBar at best will have no effect and at worst will crash (e.g., NullPointerException), because that view is not being used by an active activity

    Instead, have your code that is observing name (e.g. your activity or fragment) handle changing the visibility of this progressBar.