Hi , Is this going leak the memory , Shared view m...
# android
c
Hi , Is this going leak the memory , Shared view model concept - https://developer.android.com/topic/libraries/architecture/viewmodel#sharing Both fragments takes the reference of Activity View model , activityView model stay as long as activity stays . does it going to keep the sharedviewmodel reference once it is created till the point activity destroys ??
j
It will keep the same reference as how long the Activity is running.
so it will stay the same instance as long as the activity is not (fully) destroyed
You can scope ViewModels to live/die with Activities, Fragments and otherwise with Navigation graphs (or make some custom ViewModelStoreOwner implementation yourself but I don't think it is necessary)
so if you for example have a 1 activity architecture using the JetPack Navigation, you can create nested graphs that share a ViewModel within the graph (and once you get out of the graph the ViewModel gets cleared/destroyed)
So for example: If you have a navigation graph, and you have inside a nested registration graph, then all the fragments within the registration graph could share some RegistrationViewModel and once your registration is over, you go to some other graph and the RegistrationviewModel is cleaned up 🙂
c
I did memory profiling on this , I have single activity , numerous fragment in the app. This shared view model instance creates when I got into fragment , and then on it stays like in the screen shot.
j
yes that is how it is expected to work and it is not leaking memory
If your ViewModel is activity scoped it will be created once upon first usage and then that reference will be kept until the activity scope ceases to exist (aka activity destroy)
so if that scope is too much for you, you have to find a smaller scope, which can be a navigation graph scope or Fragment scope
c
that's what I am thinking, swallow size is nothing but size of object its self nothing but instance of sharedview model in the fragment. Inside sharedviewmodel I have one single property
Copy code
val isUserPostedSuccessfully = MutableLiveData<Boolean>(false)
if there is leak then it would have showed some number in deallocation
Yes you are true , it creates once and then that reference will be kept until activity scope . my scope is not heavy and not retaining anything heavy , I am not damaging much . is this right solution for fragment communication if this reference going to kept
j
I often use activity scoped (or sometimes navigation graph scoped) viewModels but I do have multiple activites 🙂 I would say that if it is rather a small thing it wouldn't clog the memory
👍 1