Jetpack DataStore: Improved Data-Storage System
Replace shared preferences with Jetpack DataStore
What’s DataStore?
Over the years, Android developers have become used to storing small chunks of sensitive user data via shared preferences. This approach has the following drawbacks:
- Sensitive data in shared preferences can be exposed easily
- It appears safe to invoke the shared-preference operations on a UI thread, but in reality, it’s not (due to the synchronous API that can appear safe to call on the UI thread, no mechanism for signaling errors, lack of a transactional API, and more)
DataStore is a library from the Jetpack family that provides a new data-storage solution, probably replacing shared preferences. It’s currently in the alpha stage.
Why DataStore?
It’s built using Kotlin coroutines and the Flow API, which makes it more safe and reliable than shared preferences. It offers two different approaches to save data:
- Preferences DataStore: It’s similar to
SharedPreferences, in that it has no way to define a schema or to ensure that keys are accessed with the correct type - Proto DataStore: Lets you create a schema using protocol buffers. Using protobufs allows for the persisting of strongly typed data. They’re faster, smaller, simpler, and less ambiguous than XML and other similar data formats.
In addition to that, when you store key-value pairs, only the keys will be exposed but not the content.
Database vs. DataStore
DataStore is built to store small data sets; if your requirement involves partial updates, referential integrity, or support for large/complex data sets, you should consider using Room instead of DataStore.
At the end of this article, you’ll find links to learn how to use the Room database, from its basics to more advanced options.
Integration
To use the Jetpack Datastore library, add the following line under the dependencies node in the app-level build.gradle file.
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha01"Let’s Start Coding
To better understand how to use DataStore, I took a simple real-time example, where we store an integer that indicates a user’s login status. Here, we have an enum class with all possible stages. Have a look:





