Data Store Android Kotlin

Manish Kaushik
3 min readMay 15, 2021

--

image source: google images

In this tutorial, we are going to learn about Data Store in Android using Kotlin.

Prerequisite: Kotlin, Android Concepts, Kotlin Coroutine

What is Data Store?

Jetpack Data Store is an improved data storage solution provided by Google to replace SharedPrefrences. It stores key-value pairs or typed objects with protocol buffers. DataStore uses Kotlin coroutines and Flow to store data asynchronously, consistently, and transactionally.

In simple words Data Store allows you to store data asynchronously means it will run in the background not block the main UI thread. Also Safe to call from the UI thread because the work is moved to Dispatchers.IO

  • **If you want to store a small data set then Data Store is the best choice
  • **But if you want to store a large data set or complex one go with Room

Drawbacks of Shared Preferences?

  • ANR(App not responding) issues, the reason for ANR is a long-running task on the main UI-thread
  • When you access the data in the Shared Preference, it is accessing on the UI-thread also bring the data in memory

Two types of DataStore Implementation

  1. Preference Data Store: Store in key-value pairs(mean values to assign to their respective keys) like in Shared preference. To understand think it as, (“isLogin” , true) “isLogin” is the key store's boolean status of login i.e true or false.
  2. Proto Data Store: To store custom data types

In this tutorial we will learn step by step implementation of the Preference Data Store:

Step 1: Add App level dependencies

//Data Store
implementation "androidx.datastore:datastore-preferences:1.0.0-beta01"

// Lifecycle & Coroutine components
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1"
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.4.0-alpha01"

// Kotlin components
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1"

Step 2: Create Preference Manager Class ** Used to Read/Write data from Data Store

/* Step 1 : At the top level of your kotlin file:
* property delegate created by preferencesDataStore
*to create an instance of Datastore<Preferences>*/

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_prefrences")

class UserPrefrence(private val context: Context) {

//2 : Define prefernce Key using like booleanPreferencesKey
val COUNTER_KEY = intPreferencesKey("counters")//store int value

//3 : Read value from datastore using Key
val readCounter: Flow<Int> = context.dataStore.data
.map { preferences ->
// No type safety.
preferences[COUNTER_KEY] ?: 0
}

//4 : Write value to datastore using key

suspend fun incrementCounter() {
context.dataStore.edit { prefrences ->
val currentCounterValue = prefrences[COUNTER_KEY] ?: 0
prefrences[COUNTER_KEY] = currentCounterValue + 1
}
}

Step 3: Read Value & Increment Value in Activity

//1 : create a instance of User Preference
val userPrefrence = UserPrefrence(this)

//2: get Counter value from data store when activity create & //display to textview
lifecycleScope
.launch {
binding.textView.text = userPrefrence.readCounter.first().toString()
}

//3: On button clik increment value in data store

binding.incrementBtn.setOnClickListener {

GlobalScope.launch(Dispatchers.IO) {
//icrement value to data store

userPrefrence.incrementCounter()
}

//display increment value on textview

val value = (binding.textView.text.toString()).toInt() + 1
binding.textView.text = value.toString()

}

Done

Connect with me: LinkedIn

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (1)

Write a response