<?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 Mehul Bisht on Medium]]></title>
        <description><![CDATA[Stories by Mehul Bisht on Medium]]></description>
        <link>https://medium.com/@mehulbisht?source=rss-ee4c6cdcf0bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1O9ObeNsAYpm58hF</url>
            <title>Stories by Mehul Bisht on Medium</title>
            <link>https://medium.com/@mehulbisht?source=rss-ee4c6cdcf0bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:44:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mehulbisht/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[Using Jetpack Preferences Datastore with Dagger Hilt on Android]]></title>
            <link>https://mehulbisht.medium.com/using-jetpack-preferences-datastore-with-dagger-hilt-on-android-646346656ea1?source=rss-ee4c6cdcf0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/646346656ea1</guid>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[jetpack-datastore]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mehul Bisht]]></dc:creator>
            <pubDate>Wed, 09 Jun 2021 20:45:56 GMT</pubDate>
            <atom:updated>2021-06-09T20:45:56.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYaXZm2HBquH1vktl6sEuA.png" /><figcaption>Using Preferences Datastore with Dagger Hilt</figcaption></figure><p>The Jetpack Datastore is in Beta now, and also Dagger Hilt is now stable. With version <strong>1.0.0-alpha07 </strong>of Datastore the API has changed a bit now.</p><pre>Api Changes:</pre><pre>The <strong>Context.createDataStore</strong> extension function has been removed and replaced with <strong>globalDataStore </strong>property delegate. Call globalDataStore once at the top level in your kotlin file.</pre><pre>DataStore will now <strong>throw an</strong> <strong>exception </strong>if there are multiple active DataStores for the same file. If you were not managing your DataStore as a <strong>Singleton</strong> or were not ensuring that no two instances of DataStore are <strong>simultaneously active</strong> for a file then you may now see <strong>exceptions </strong>when <strong>reading </strong>or <strong>writing </strong>to DataStore. These can be fixed by managing your DataStore as a <strong>Singleton</strong></pre><p>You can view the changes here:</p><p><a href="https://developer.android.com/jetpack/androidx/releases/datastore#1.0.0-alpha07">https://developer.android.com/jetpack/androidx/releases/datastore#1.0.0-alpha07</a></p><p>In this article, we will see how to provide a dependency for Preferences Datastore with Hilt after the recent API changes.</p><p>Firstly, we should have all the required dependencies for preferences Datastore, Hilt, and lifecycle.</p><p><strong>Datastore</strong></p><pre>implementation <strong>&quot;androidx.datastore:datastore-preferences:1.0.0-beta01&quot;</strong></pre><p><strong>Hilt</strong></p><pre><strong>def </strong>hiltVersion = <strong>&quot;2.35&quot;<br></strong>implementation <strong>&quot;com.google.dagger:hilt-android:</strong>$hiltVersion<strong>&quot;<br></strong>kapt <strong>&quot;com.google.dagger:hilt-android-compiler:</strong>$hiltVersion<strong>&quot;</strong></pre><p><strong>Lifecycle</strong></p><pre><strong>def </strong>lifecycle_version = <strong>&quot;2.3.1&quot;<br></strong>implementation <strong>&quot;androidx.lifecycle:lifecycle-runtime-ktx:</strong>$lifecycle_version<strong>&quot;</strong></pre><p>Don’t miss the <strong>Hilt </strong>and <strong>Kapt </strong>Plugins</p><pre>plugins <strong>{<br></strong>...<br>   id <strong>&#39;kotlin-kapt&#39;</strong>    <br>   id <strong>&#39;dagger.hilt.android.plugin&#39;<br>}</strong></pre><p>and add the classpath</p><pre>dependencies <strong>{<br>...<br>   def </strong>hiltVersion = <strong>&quot;2.28.3-alpha&quot;<br>   </strong>classpath <strong>&quot;com.google.dagger:hilt-android-gradle-plugin:</strong>$hiltVersion<strong>&quot;<br>}</strong></pre><p>Now that we are done with the setup, let’s start getting everything together. We will create an interface <em>PreferenceStorage </em>as shown. You can create multiple keys as well just like the <strong>PREF_LOGGED_IN</strong> here. In this example we are only checking if user was logged in before or not with a <em>booleanPreferencesKey . </em><strong>Save </strong>function will be used to set the new value of the key and <em>isLoggedIn </em>is a <strong>flow </strong>that we will be collecting later to get the logged in status.</p><pre><strong>interface </strong>PreferenceStorage {<br><br>    <strong>suspend fun </strong>save(isLoggedIn: Boolean)<br>    <strong>val isLoggedIn</strong>: Flow&lt;Boolean&gt;<br><br>    <strong>object </strong>PreferencesKey{<br><br>        <strong>val PREF_LOGGED_IN </strong>= <em>booleanPreferencesKey</em>(<strong>&quot;logged_in&quot;</strong>)<br>    }<br>}</pre><p>Then, we will make a <strong>module </strong><em>AppModule </em>for dependency injection and provide <em>dataStore </em>as shown:</p><pre><strong>@InstallIn</strong>(SingletonComponent::<strong>class</strong>)<br><strong>@Module<br>object </strong>AppModule { </pre><pre><strong> @Singleton<br> @Provides<br> fun </strong>provideDataStore(<br>     <strong>@ApplicationContext </strong>context: Context,<br> ): DataStore&lt;Preferences&gt; {<br><br>     <strong>val </strong>datastore = PreferenceDataStoreFactory.create(<br>         migrations = <em>listOf</em>(<br>         <em>SharedPreferencesMigration</em>(context,<em>PREFS_NAME</em>)<br>         ),<br>         scope = <em>CoroutineScope</em>(Dispatchers.<strong>Default</strong>)<br>     ) <strong>{<br>         </strong>context.<em>preferencesDataStoreFile</em>(<em>PREFS_NAME</em>)<br>     <strong>}<br>     return </strong>datastore<br> }<br>}</pre><p>And then we will create a class <em>DataStorePreferenceStorage </em>that will implement this <strong>interface </strong>and receive this <em>datastore </em>as a dependency. Here, the <strong>PREFS_NAME </strong>is the name of our preferences datastore. We will override the methods from <strong>interface </strong>to <em>save </em>the keys and collect them as <em>flow </em>later.</p><pre><strong>@Singleton<br>class </strong>DataStorePreferenceStorage <strong>@Inject constructor</strong>(<br>    <strong>private val dataStore</strong>: DataStore&lt;Preferences&gt;<br>): PreferenceStorage {<br><br>    <strong>companion object </strong>{<br>        <strong>const val PREFS_NAME </strong>= <strong>&quot;auth_prefs&quot;<br>    </strong>}<br><br>    <strong>override suspend fun </strong>save(isLoggedIn: Boolean) {<br>        <strong>dataStore</strong>.edit <strong>{ </strong>settings <strong>-&gt;<br>            </strong>settings[<em>PREF_LOGGED_IN</em>] = isLoggedIn<br>        <strong>}<br>    </strong>}<br><br>    <strong>override val isLoggedIn</strong>: Flow&lt;Boolean&gt; =<br>        <strong>dataStore</strong>.<strong>data</strong>.<em>map </em><strong>{ it</strong>[<em>PREF_LOGGED_IN</em>] ?: <strong>false }<br></strong>}</pre><p>Now, we need to provide this class <em>DataStorePreferenceStorage </em>in our <em>AppModule</em></p><pre><strong>@InstallIn</strong>(SingletonComponent::<strong>class</strong>)<br><strong>@Module<br>object </strong>AppModule {<br> <br> <strong>val </strong>Context.<em>datastore </em><strong>by </strong><em>preferencesDataStore</em>(<br>     name = DataStorePreferenceStorage.<strong>PREFS_NAME</strong>,<br>     produceMigrations = <strong>{ </strong>context <strong>-&gt;<br>         </strong><em>listOf</em>(<br>             <em>SharedPreferencesMigration</em>(<br>                 context,<br>                 DataStorePreferenceStorage.<strong>PREFS_NAME<br>             </strong>)<br>         )<br>     <strong>}<br> </strong>)<br><br> <strong>@Singleton<br> @Provides<br> fun </strong>providePreferencesStorage(<strong>@ApplicationContext </strong>context:  Context): PreferenceStorage =<br>     DataStorePreferenceStorage(context.<em>datastore</em>)</pre><pre>...<br>}</pre><p>We are close to the end of this article now! Inside our <em>view</em>, (<em>Activity </em>in this case) we need to annotate with <strong>@AndroidEntryPoint </strong>and <em>Inject </em>this class <em>DataStorePreferenceStorage </em>as shown:</p><pre><strong>@Inject<br>lateinit var dataStorePreferenceStorage</strong>: DataStorePreferenceStorage</pre><pre><strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>...</pre><p>For saving a value to our Preferences Datastore we just need to launch a <em>lifecyclescope </em>and call our <em>Save </em>method like this:</p><pre><em>lifecycleScope</em>.launchWhenStarted <strong>{</strong></pre><pre><strong> dataStorePreferenceStorage</strong>.save(<strong>true</strong>)<br>...<br>}</pre><p>And for reading values, we just need to observe the <em>flow </em>that we are getting from the <em>DataStorePreferenceStorage:</em></p><pre><em>lifecycleScope</em>.launchWhenStarted <strong>{<br><br>    dataStorePreferenceStorage</strong>.<strong>isLoggedIn</strong>.collect <strong>{ </strong>isLoggedIn <strong>-&gt;<br><br>        if</strong>(!isLoggedIn) {</pre><pre>        // User isn&#39;t logged in, take action.<br>        }<br>     }<br>  } </pre><p>I hope I was able to explain how to provide the Preferences Datastore with Dagger Hilt as a <em>Singleton</em>.</p><p>You can find the final code for this article over here:</p><p><a href="https://github.com/Mehul-Bisht/DataStore-Demo">Mehul-Bisht/DataStore-Demo</a></p><p>If you want to dive deeper into writing test cases and more, head over to this Google I/O sample app and check it out!</p><p><a href="https://github.com/google/iosched">google/iosched</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=646346656ea1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>