Preferences DataStore


This is time to say bye bye to SharePreferences. Jetpack DataStore is new solution to store data. It is replacement of SharePreferences. Preferences DataStore is one way of DataStore to save data.

In share preference, we can only save data in key-value. It allows us to store data in key-value pair and in form of object as well.

It saves data using Async Api and it builds with coroutines and flow.


DataStore provides two different implementations :

  1. Preferences DataStore : It stored data in key-value pair.
  2. Proto DataStore : It stores a custom data type. We need to define a scheme using protocol buffers.

In this blog, we will cover Preferences DataStore only.


Add Dependency

Create a Preference DataStore

Now, create a instance of datastore. It will create a file name as “MyDataStore”.

createDataStore” is a extension function created on Context.  Method will return DataStore instance.

Create Key for Data

To save the data, first we need to create a key for our value.

This will define the name of key and it’s type.

If you wanna save int value, you will have to use ‘intPreferencesKey‘.

Write Data

edit‘ method is used to save data in DataStore. It is suspend function. It should be called by either coroutines or another suspend function.

Call a suspend function :

We use Global scope to create coroutines.

Check following link for kotlin coroutines : Kotlin Coroutines

Read Data 

DataStores provides data property to expose the value.

We create string type flow object.

Flow :

To learn more about flow, check following link : Kotlin Flow

Hopefully, this blog will be helpful for you.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.


Webkul is a truly trusted and supported IT Company to develop business ideas for e-commerce. They provide professional support after deploying the solution to production and be responsible to act for fixing the reported issues or system errors. We highly encourage to deal with Webkul for business development.

Hussein Zawia

Hussein Zawia

Co-founder, 24Dokan

Talk to Sales


Live Chat
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home