<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Varun Naik on Medium]]></title>
        <description><![CDATA[Stories by Varun Naik on Medium]]></description>
        <link>https://medium.com/@varunnaik?source=rss-33f53ee12e8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0Wf0B1VyOajqcFJN.jpg</url>
            <title>Stories by Varun Naik on Medium</title>
            <link>https://medium.com/@varunnaik?source=rss-33f53ee12e8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 01:26:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varunnaik/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Resolving mystery of ViewModel persistence on configuration change]]></title>
            <link>https://medium.com/@varunnaik/resolving-mystery-of-viewmodel-persistence-on-configuration-change-ea54ddcfb520?source=rss-33f53ee12e8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea54ddcfb520</guid>
            <category><![CDATA[androidviewmodel]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[Varun Naik]]></dc:creator>
            <pubDate>Fri, 13 Dec 2019 20:15:27 GMT</pubDate>
            <atom:updated>2019-12-14T11:38:00.847Z</atom:updated>
            <content:encoded><![CDATA[<p>What is a ViewModel?</p><p>As the official definition says “The <a href="https://developer.android.com/reference/androidx/lifecycle/ViewModel.html">ViewModel</a> class is designed to store and manage UI-related data in a lifecycle conscious way.”</p><p>Why is it important?</p><p>Coding in android used to be lawless zone before and somewhat still is. There was no proper way of doing things and no hard restrictions on it. With architecture components, coroutines etc comes a way to do things which will be more understandable and with less boilerplate, which in the end will facilitate to make architecture and testing a less intimidating zone.</p><p>ViewModel is promoted by google itself :P</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcdW1QSdCzYXjmDt-tiscQ.png" /></figure><p>Let’s come back to the main point, how is it able to retain even after the configuration change?</p><p>From definition “lifecycle conscious” is one of the key part where we need to look into. We will come back to this later in the document.</p><p>One of the initial implementations involved keeping a fragment inside activity named as HolderFragment and making it responsible for keeping the ViewModelStore which stores/provides viewmodel. And configuration was handled on this fragment by setting <em>setRetainInstance(true) </em>so that it will not be destroyed. You can look it up here: <a href="https://android.jlelse.eu/deep-dive-inside-of-androids-viewmodel-architecture-components-e6756dc0bb11">https://android.jlelse.eu/deep-dive-inside-of-androids-viewmodel-architecture-components-e6756dc0bb11</a></p><p>But after so many modifications and updates in androidx, it has been drastically changed. But its just two methods inside an activity which creates this magic and they are:</p><p><a href="https://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance()">onRetainNonConfigurationInstance()</a> - Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration.</p><p><a href="https://developer.android.com/reference/android/app/Activity.html#getLastNonConfigurationInstance()">getLastNonConfigurationInstance()</a>- Retrieve the non-configuration instance data that was previously returned by <a href="https://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance()">onRetainNonConfigurationInstance()</a>.</p><p>In the latest code, if you check the inheritance structure of you activity you will find-</p><p>YourActivity : AppCompatActivity :-&gt; FragmentActivity :-&gt; ComponentActivity :-&gt; androidx.core.app.ComponentActivity :-&gt; Activity :-&gt;……. Context</p><p>The code we are looking for is in ComponentActivity where your viewmodelStore is a lazy class variable. So the first time it is fetched, it will be instantiated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPuLiwh0HuOe0DXfnJeDJQ.png" /><figcaption>Figure B. Method used to fetch viewModelStore internally</figcaption></figure><p>And when your activity changes configuration, <a href="https://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance()">onRetainNonConfigurationInstance</a>() is called and it stores the viewModelStore in NonConfigurationInstances object and returns it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uek_8VUP8geoi6OWq7MFsQ.png" /><figcaption>Figure C. Implementation of onRetainNonConfigurationInstance()</figcaption></figure><pre>static final class NonConfigurationInstances {<br>    Object custom;<br>    ViewModelStore viewModelStore;<br>}</pre><p>And that’s pretty much it. Now this custom object can be fetched after configuration change from getLastNonConfigurationInstance() which getViewModelStore() is using internally(refer to figure B). And it checks if nc != null then retain the viewmodelstore else create a new one.</p><p><strong>Now, coming to the “lifecycle conscious” part. When will it actually be cleared?</strong></p><p>ComponentActivity is LifecycleOwner, it attaches an observer on lifecycle of activity and when it gets the event as Lifecycle.Event.<em>ON_DESTROY </em>it checks if activity is being destroyed because of configuration or not. If it is not being destroyed because of configuration change, it calls the clear() method of viewModelStore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EMAAOplY0rIpmJcsn_44w.png" /><figcaption>Figure D. clearing viewmodel store</figcaption></figure><p>And folks, this is how viewmodel is retained after configuration change in activity.</p><p><strong>For fragments, case is little bit different(don’t worry its not much different).</strong></p><p>All you need to know is fragmentManager is provided by the host activity. And fragment manager class has an object of FragmentManagerViewModel, which is basically responsible for storing viewModelStore in a HashMap&lt;String, ViewModelStore&gt;.</p><p>Initially it will create a new ViewModelStore for every new fragment and save it in map with fragment id as key.</p><p>When configuration is changed, object of FragmentManagerViewModel will be saved in viewModelstore in NonConfigurationInstances of activity(discussed above) and after recreation when the host attaches again, activity will provide the FragmentManagerViewModel which will have the HashMap&lt;String, ViewModelStore&gt; mViewModelStores and it retains the store again from map.</p><p><strong>When will the fragment’s viewmodel gets cleared?</strong></p><p>One more class comes in the play for this. You might have heard about FragmentStateManager. Method onDestroy() is called in this class and it checks whether fragment is being removed naturally or because of configuration change. If its being destroyed naturally then call the clearNonConfigState() in FragmentManagerViewModel, which first will clear the viewModelStore in map then remove it from the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8deKGKC46NRO1kcLvnXMg.png" /><figcaption>Figure E. clearing viewmodel from fragment</figcaption></figure><p>if (article.isHelpful) {</p><p>// If you’re happy and you know it, press on clap :P</p><p>pressOnClap();</p><p>} else {</p><p>//This is my first article. Incase I have missed something or you feel //something is incorrect</p><p>doLetMeKnow(issue);</p><p>}</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea54ddcfb520" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>