ViewModels and LiveData: Patterns + AntiPatterns
Jose Alcérreca

I’ve just started using Android Architect Components and I did not understand one thing: why it is not allowed to store reference to the View (Activity or Fragment) in ViewModel class? Documentation says that it can cause memory leak. It is true, but I can manually clear this reference in View’s onDestroy() method and send new reference to ViewModel class in View’s onCreate() (or onCreateView()) method to prevent leak.

ViewModel with reference to View allows to make Model — View — Presenter pattern (use ViewModel class as a Presenter).


Will you please explain me can I avoid memory leaks using ViewModel class as a Presenter with reference to View which I will clear and update manually in View’s onCreate() (or onCreateView()) and onDestroy() methods?

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.