I'm trying to reference a Spinner view and its value from HomeViewModel
that is populated with a list of strings in the HomeFragment
and declared in the XML layout file of the fragment.
This spinner contains a list of languages.
Depending on which language is selected, I assign a different variable through spinner.getSelectedItem().toString()
in the HomeViewModel
. Problem is, spinner
is not defined or referenced there, and I wouldn't do the processing on my HomeFragment
because I'll run some heavy code on it so as not to block it. How do I call the spinner? Is it wrong to use the HomeViewModel
as a kind of coroutine?
You should never do this because it causes a memory leak. From the documentation:
Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.
What if you create a view model's method passing the selected language as parameter and call the method from within the view (Fragment)?