DataStore like many other jetpack functionalities was earlier being used inside Google and now it is being released for public. Data Store is meant for storing small amounts of data like settings. It is actually a betterment over Shared Preferences.
Shared Preferences has issues like
- It doesnt have any consistency guaranties -i.e. doesn’t ensure never read a value that is not persisted
- Cannot implement a shared counter without external synchronisation
- It is synchronous, blocks the current thread while reading and writing.
Data Store primarily stores key values in a data store. It can also be used for storing typed objects like Json responses and protobufs format.
- Preference DataStore, like SharedPreferences, has no way to define a schema or to ensure that keys are accessed with the correct type.
- Proto DataStore lets you define a schema using Protcol buffers Using Protobufs allows persisting strongly typed data.
The recommended max size is 10-20 KB. When you use protobuf – you define a schema and Java code is generated to serialize to and deserialize from binary. DataStore gives atomic Read – Modify – Write guarantee. DataStore uses Kotlin coroutines and Flow to store data asynchronously. Data store currently exposes two apis. The first one is “update data”. It runs on a coroutine and returns a transform call back. It takes a lambda as input. The second api is data – it returns a flow of datastore type. DataStore has a suspend func in update data which ensures that on flow finishing latest data is written. Data Store Api are async. By default they use dispatchers.io for both reading and writing.
It is easy to migrate from SharedPreferences to DataStore. Migrating from SharedPreferences to Datastore will be more about storing data from say sync to async. Kotlin coroutines provide the runBlocking() coroutine builder to help bridge the gap between synchronous and asynchronous code. You can even implement your own migration to migrate or to change data store types.
Changes Required to build.gradle file to include DataStore in app:-
DataStore Typed

Datastore Preferences

For sample code on how to use Data store, please visit:-
https://android-developers.googleblog.com/2020/09/prefer-storing-data-with-jetpack.html
Datastore is currently in alpha and is a part of Jetpack library
Leave a Reply