ViewModels and LiveData: Patterns + AntiPatterns
Jose Alcérreca
7.9K37

Hello! 
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).

Example:
https://gist.github.com/Denis-Avenger/2645b0cfaf22cb70b71de40cff59a4f0

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.