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
Now, create an Application class DataStore as follows
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
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
This will provide a Singleton of DataManager to our application
It’s time to create a layout for our main activity as follows:
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