Welcome Preferences DataStore ๐Ÿš€

Rahul Ray
2 min readOct 4, 2020

Hello developers, in this article I am going to cover a new member of Jetpack Library ๐Ÿš€ called DataStore.

We are working on shared preferences for a long time to store some of the data locally in our android apps and we know how shared preferences proved to be very useful to support our use cases.

To make our lives easier Android has introduced DataStore to implement Shared Preferences in our apps in a more efficient way.

DataStore provides two types of implementation,i.e; Preferences DataStore and Proto DataStore. Today we are looking at Preferences DataStore.

So, why should we use Preferences DataStore? ๐Ÿ˜•

  • It is an Async API that can be used via Flow
  • It is safe to call on UI thread since work is moved to Dispatchers.IO under the hood
  • It can signal errors
  • It is safe from runtime exceptions
  • It has a transactional API with strong consistency
  • It handles data migration from Shared Preferences

This dude has some Advantages, right! ๐Ÿ˜ƒ

Now, letโ€™s directly jump into the code ๐Ÿ’ป

For this example I have used Dagger-Hilt to provide dependency Injection.

Letโ€™s update our build.gradle files like this

build.gradle(app)
build.gradle (project)

Now, create an Application class DataStore as follows

DataStore.kt

Next, we will create a DataManager class where all our logic will go. For this example I have stored userโ€™s name, GitHub username and favorite number

DataManager.kt

Here the storeData function is made suspend because to make it asynchronous and we love coroutines๐Ÿ’›

Next, we will create our AppModule which will provide this DataManager

AppModule.kt

This will provide a Singleton of DataManager to our application

Itโ€™s time to create a layout for our main activity as follows:

activity_main.xml

Finally here comes our MainActivity ๐Ÿ˜Œ

Here we have observed on our Preferences Keys as LiveData and made them visible.

Everything is pretty smooth and straight forward in this implementation ๐Ÿ˜Œ

Now, letโ€™s run and test our app

It is working fine now ๐ŸŽ‰ . See you in the next story..

For complete code reference checkout the following repository

--

--