Welcome Android developers 👋. This article is the first part of a series article based on the new Jetpack library🚀 i.e. DataStore🗄️. Currently, it’s alpha version is released. Let’s see what’s DataStore and why DataStore.
What is DataStore 🤷♀️?
Jetpack DataStore is a data storage solution.
It allows us to store key-value pairs (like SharedPreferences) or typed objects with protocol buffers (We’ll see it in next article).
DataStore uses Kotlin, Coroutines and Flow to store data synchronously with consistency and transaction support 😍.
In short, it’s the new data storage solution which is the replacement of SharedPreferences.
Why DataStore 🤷♂️
First and my favourite reason 😃 — Built with❤️ Kotlin, Coroutines and Flow.
If you have used SharedPreferences you might abuse or blamed it for something 😆 then DataStore is here to rescue!
SharedPreference has some drawbacks like it provided synchronous APIs -but it’s not MAIN-thread-safe! whereas DataStore is safe to use in UI thread because it uses Dispatchers.IO under the hood👀.
It’s safe from runtime exceptions!❌⚠️. What would be more satisfying that? 😅
It also provides a way to migrate from SharedPreferences 😍.
It provides Type safety! (Using Protocol buffers).
These are some reasons which encourage us to use DataStore and finally say goodbye to beloved SharedPreferences 👋.
# That’s not only the reason —
DataStore provides two different types of implementations to store data.
Preference DataStore - This uses key-value pairs to store data. But it doesn’t provide type-safety :
Proto DataStore - It stores data as a custom type with specified schema using Protocol Buffers (We’ll see about it in the next article).
I think that’s enough introduction to DataStore. It’s time to write some code👨💻😎.
Let’s begin code 👨💻
You can simply clone or refer this repository to get example code demonstrating DataStore📁.
We’ll develop a sample Android application which stores a UI mode preference from user i.e. 🌞 Light Mode or 🌑 Dark Mode.
First of all, let’s add a Gradle dependency in build.gradle of your app module. Currently 1.0.0-alpha01 is the latest release. You can keep an eye here to get info about the latest version.