Answer the question
In order to leave comments, you need to log in
Will there be a leak when using Shared ViewModel?
Good evening. I searched for a long time on the Internet and did not find an answer, so I decided to write here. Let's say I use a SharedViewModel in a fragment that has a lifeCycleOwner activity. This activity does not complete the work for a long time, but fragments are constantly changing in this activity. In fact, the SharedViewModel used in the fragments is not destroyed and it turns out that the link to the fragments remains and they remain in memory. However, LeakCanary did not fix any memory leaks. But when I did tests for the next replacement of fragments in the activity about 100 times, I got a memory area that was not collected by the garbage collector, or so it seemed to me. The question is whether the fragments that use the SharedViewModel remain in memory until the end of the activity or not?
Answer the question
In order to leave comments, you need to log in
In this case, there is no leakage. A link to a fragment will not appear in the ViewModel from anywhere unless you pass it there. This means that the lifetime of the ViewModel does not affect the lifetime of the fragment. The fact that a fragment stores some references cannot affect its lifetime in any way. The object graph is directed.
And what for to store references to fragments? You need to give control over them to the fragment manager. He himself knows when to throw out this or that fragment from memory. In my application, I specifically ensured that the fragments remained in memory and were not recreated too often. To do this, in the transaction, I had to do without replace, attach and detach, and use show and hide. I do not store links to fragments anywhere and find them when necessary through the fragment manager by tag. And if the fragment is not found, I create a new instance.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question