Table of contents
No headings in the article.
This post is the first in a series on memory leaks in android development. So we kick off with the most trivial cases. In Android development sometimes you are faced with a need to exchange(or pass) data from fragment to fragment or from fragment to activity. There are two options to resolve this:
First is you may utilize a shared viewModel and secondly the Fragment Result API. The recommended option depends on the use case. To share persistent data with any custom APIs, you should use a ViewModel. For a one-time result with data that can be placed in a Bundle, you should use the Fragment Result API.
It would be nice to go through each method with examples but it would be out of the scope of this article however you can check [developer.android.com/guide/fragments/commu.. for more. Yea back to the subject "avoiding memory leaks" hahaha.
As your project gets larger if you are not careful about following standard in android development especially in the case of transferring data and navigation, you might create potential memory leaks and unimaginable redundancy.
To avoid these pitfalls it is recommended that you have seperate View Model for each activity or fragment. Having same View Model for different activity and/or fragments will lead to inconsistent data and memory leaks.
Ideally fragment and activity should have their own independent View Model. For example:
- BagsActivity and BagsViewModel
- BagsDetailFragment and BagsDetailViewModel
This separates the code by following the Separation of concerns principle and you will get benefit from this as your application logic grows. And If you are looking for shared behaviour/data, please used Shared View Model.
It is also important that when using a shared view model you instantiate it separately in the class(fragment or activity) which you intend to use it. For instance instead of using the View Model from BagsActivity you should initialise it completely in BagsDetailFragment.
If you have a BagsViewModel thats for the BagsActivity and you want to utilize it in BagsDetailFragment it is important that you initialise it separately in the fragment to avoid memory leaks. eg,
// in your fragment do
viewModel = ViewModelProvider(this,ViewModelProviderFactory).get(BagsViewModel::class.java)
In this article we have discussed how important it is to have separate View Models for your application components (in this case activities and fragments) or use a shared view model when necessary .In doing so you make it easy to maintain you application as it grows and avoid potential memory leaks. see on the next one .