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