Issue
After initializing my viewModel from the activity, I initialize the sharedPreference variable (sharedPrefs) in the viewModel from the activity.
Activity code:
housemate2ViewModel = ViewModelProvider(this)[Housemate2ViewModel::class.java]
housemate2ViewModel.sharedPrefs = this.getSharedPreferences(mainSharedPrefTag, Context.MODE_PRIVATE)
This looks like the viewModel has a reference to the activity and could cause a memory leak. To solve this I make this variable in the viewModel null when the activity is destroyed. I have seen a solution to this is to extend AndroidViewModel instead of ViewModel. My goal in asking this is mainly to understand the problems this could cause, but also to know what is the correct way of solving this. Any answer helps.
I wrote this in kotlin but an answer in java is fine.
Solution
As you've mentioned, it's best to not depend on the activity. Each time you recreate your activity, for example on orientation change, the viewmodel remains the same. Setting the variable to null is a workaround. You would have to reinitialise the shared preferences each time and there's a greater chance of error.
The View should only observe and send user actions to the viewmodel.
You could make use of the AndroidViewModel
to get the application context, but the recommended practice is to avoid using objects that have a lifecycle in ViewModels.
One way you could go about decoupling this is by using a dependency injection framework. You could inject your shared prefs into the viewmodel constructor or into your repository class and not depend on the activity. This makes it so you could test things easier as well.
Answered By - Filip Petrovski
Answer Checked By - Timothy Miller (JavaFixing Admin)