0

I'm try to update my school project with android architecture components. In these days I'm researching about ViewModel component in architecture components. I read lots of articles.

I know using viewmodel is used to provide data to the UI and survive configuration changes. But my question is this will be a cause of memory leak?. As an example If the reference is not cleared before the Activity’s lifecycle completes, it will be a memory leak. Most of the time Context will cause to the memory leak, because of Contexts contain many references to large amounts of memory.

If viewmodel will be the cause of the memory leak how to avoid it?

Thanks in advance.

References :

https://developer.android.com/topic/libraries/architecture/viewmodel

https://google-developer-training.gitbooks.io/android-developer-advanced-course-practicals/unit-6-working-with-architecture-components/lesson-14-room,-livedata,-viewmodel/14-1-a-room-livedata-viewmodel/14-1-a-room-livedata-viewmodel.html#task7intro

Pasindu Weerakoon
  • 588
  • 1
  • 11
  • 39
  • 1
    if you need context in viewmodel you should use AndroidViewModel. Also you should not keep anything related to view in ViewModel. That's why you use livedata and observe the changes in activities or fragments – Raghunandan Aug 14 '18 at 16:10
  • `As an example If the reference is not cleared before the Activity’s lifecycle completes` - which reference? – Anatolii Aug 14 '18 at 16:12
  • @Raghunandan : Thanks for your answer. That means viewmodel will cause to the memory leak when I pass the context to the viewmodel. Because when we rotate the device activity/fragment will be destroyed, but viewmodel holds all the reference data inside it, this will be a memory leak. – Pasindu Weerakoon Aug 14 '18 at 16:56
  • 1
    Yes activity context should not be in view model . read the conclusion part at https://medium.com/google-developers/viewmodels-a-simple-example-ed5ac416317e – Raghunandan Aug 15 '18 at 05:06
  • @Raghunandan : Appreciate your help. Thanks. – Pasindu Weerakoon Aug 15 '18 at 05:36

0 Answers0