Explore Android | DataStore API (Part-2)

Meet
3 min readSep 6, 2022

--

Image by storyset on Freepik

In PART-1, we have seen how to use DataStore API, and how to store/get data and read them asynchronously. We have also seen how we can observe changes through ViewModel and update our UI.

In this Part-2, we will see How to read data synchronously, How to clear the stored preferences, locate and view preference files in storage, migrating data from old Shared Preferences to DataStore.

Synchronous Operation

sometimes we need to read the data synchronously to perform some logic or due to some dependency that doesn't provide asynchronous APIs.

Let’s see how we can read data synchronously,

As we can see we have two ways to read the data. If we use runBlocking then it will block the UI thread and to deal with this we can use lifecycleScope to avoid blocking the UI thread.

Clear All Stored Preferences

It is very easy to clear all the stored data with just one line of code. Here we are using edit so we have to use suspend function.

Locate & view the DataStore file in the storage

we can see it is located inside the data directory.

dir/data/data/com.example.learningdatastore/files/datastore/MyDataStore.preferences_pb

If we open the file we can see the username that we have stored.

Migrating data from old Shared Preferences to DataStore.

DataStore API provides an easy way to migrate all the stored values from Shared Preference to DataStore with just a few lines of code.

Let’s say we have stored some value in the Shared Preferences with the key name “MySharedPrefUserName” and the name of our Shared Preferences XML file is “MySharedPref”.

Now to migrate the data we just need the name of the Shared Preferences file “MySharedPref” and need to add the migration code where we initiated the DataStore.

Now if you run the app it will delete the old Shared Preferences XML file from the storage and migrate all the keys in the DataStore file. Let’s see what it looks like.

We can see the highlighted key is from Shared Preference and successfully migrated to the DataStore.

Thanks for reading this article❤️. If you found this article useful then hit that clap button 👏.

--

--

Meet

Full-time Android Developer, Tech Enthusiast, Knows Flutter, React Native, Web Development Etc…