avatarSiva Ganesh Kantamani

Summary

Jetpack DataStore is a new data-storage solution that aims to replace shared preferences, providing a safer and more reliable way to store small chunks of sensitive user data.

Abstract

Jetpack DataStore is a new data-storage library from the Jetpack family that is currently in the alpha stage. It addresses the drawbacks of using shared preferences for storing small chunks of sensitive user data by providing a more secure and reliable solution. DataStore is built using Kotlin coroutines and the Flow API, and offers two different approaches to save data: Preferences DataStore and Proto DataStore. Preferences DataStore is similar to SharedPreferences, while Proto DataStore lets you create a schema using protocol buffers. DataStore is designed to store small data sets, and if your requirement involves partial updates, referential integrity, or support for large/complex data sets, you should consider using Room instead of DataStore.

Bullet points

  • Jetpack DataStore is a new data-storage solution that aims to replace shared preferences
  • DataStore is built using Kotlin coroutines and the Flow API, making it more safe and reliable than shared preferences
  • DataStore offers two different approaches to save data: Preferences DataStore and Proto DataStore
  • Preferences DataStore is similar to SharedPreferences, while Proto DataStore lets you create a schema using protocol buffers
  • DataStore is designed to store small data sets, and if your requirement involves partial updates, referential integrity, or support for large/complex data sets, you should consider using Room instead of DataStore.

Jetpack DataStore: Improved Data-Storage System

Replace shared preferences with Jetpack DataStore

Photo by Mark Timberlake on Unsplash

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:

Create your DataStore

The next step is to create the DataStore. For this, we need to create a Kotlin class in which we’ll use the context.createDataStore extension function to create the DatasSore. Have a look:

Creating keys

We’ll create the preferencesKey inline function by defining the result type. Have a look:

companion object {
    val USER_STATUS = preferencesKey<Int>("user_status")
}

Save and Retrieve Data

Now that we’ve created our DataStore andkeys, it’s time to save the user’s status. We’ll save an integer with values 1, 2, 3, and 4 representing STARTER, ONBOARDING_LEVEL_1, ONBOARDING_LEVEL_2, and VERIFIED, respectively.

Save

To save key-value pairs in the DataStore file, we have to use the edit function, which updates the value. Here, we use the suspend function to save values. Have a look:

Retrieve

To retrieve values from the DataStore, we use the Flow API. One of the main advantages of using Flow is every time a new value is updated in the DataStore, we get notified. So we no longer need to check for updated values anymore.

Instead of handing the integer to the user-status case at the call site, we can use functions like map to transform the data into an appropriate data type. Now, let’s bring the pieces together so they make more sense. Have a look:

Access From Android Components

Now that we’re done with the preference manager, let’s figure out how to invoke setUserStatus from an Android activity. Have a look:

As setUserStatus is a suspend function, we’ve used a lifecycleScope to launch a coroutine.

Retrieving the data center’s data is similar; here, we use collectLatest from the Flow API by warping it with a lifecycleScope. Have a look:

Conclusion

That’s all for now. Hope you learned something useful. Thanks for reading!

Jetpack library resources

Room library resources

AndroidDev
Programming
Jetpack
Mobile
Android
Recommended from ReadMedium