Pick the fix
A ViewModel keeps private val activity: Activity. After a few rotations, memory grows. What's the fix?
Hint 1 of 1
Which lives longer, the ViewModel or the Activity?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Remove the reference; pass data in and expose state out, using the application context if needed
Correct. The ViewModel outlives each Activity instance and leaks it.
Why not the others?
- B Make the reference a WeakReference and keep using it. It avoids the leak but the design is still wrong; you'd call into a dead Activity.
- C Clear it in onDestroy. The ViewModel doesn't get onDestroy; and it would still hold the new one.
- D Use
lifecycleScopein the ViewModel. ViewModels don't have a lifecycleScope; they use viewModelScope.