Prefer Storing Data with Jetpack DataStore in Android

September 24, 2021 Publish By : EXPERT APP DEVS 3 min read Viewed By : 558
storing data with jetpack datastore

In mobile applications development, some data has to be persisted to make the application startup faster and increase app performance, reduce API Requests or handle data in offline mode. In this blog, you learn how to store data in your Android application, especially with Jetpack DataStore. To introduce this I am going to give a walkthrough about the three mainly used methods or approaches. I am going to covered follow topics in this blog:

  • SharedPreferences
  • Preferences DataStore
  • Proto DataStore

Summary of SharedPreferences storage solutions, I will focus on the differences between SharedPreferences and DataStore. Related to the DataStore, I added the implementation steps for SharedPreference and Preferences DataStore.

SharedPreferences

Android provides multiple ways of storing data in your android application. One of these methods is called SharedPreferences. Shared Preferences allow you to store and retrieve data in the form of key, value pairs.

you need to call a method called the getSharedPreferences() method for use of SharedPreferences that returns a SharedPreference instance that is indicated to the file that contains the values of preferences.

Implementation:

Add required gradle dependency:
implementation "androidx.preference:preference-ktx:1.1.1"

Saving user data to SharedPreferences:

fun saveUserInfo(user: User) {
sharedPref.edit {
putString(PREF_FIRST_NAME, user.firstName)
putString(PREF_LAST_NAME, user.lastName)
putString(PREF_EMAIL, user.email)
putLong(PREF_BIRTH_DAY, user.birthDay)
}
}

Get user information from SharedPreferences:

fun getUser(): User {
val firstName = sharedPref.getString(PREF_FIRST_NAME, "")
val lastName = sharedPref.getString(PREF_LAST_NAME, "")
val lastName = sharedPref.getString(PREF_EMAIL, "")
val birthDay = sharedPref.getLong(PREF_BIRTH_DAY, 0)

return User(firstName = firstName ?: "", lastName = lastName ?: "", email = email ?: "", birthDay = birthDay)
}

Preferences DataStore

Preferences DataStore easily replaces the SharedPreferences. The concept behind Preference DataStore is mostly similar to SharedPreferences. It uses key-value pairs to store data and also does not provide type safety. If you’re currently using SharedPreferences to store data offline, target migrating to DataStore instead of SharedPreferences.

Setup Your Project:

You need to add a dependency in your app level build.gradle file.
dependencies {
// Preferences DataStore
implementation "androidx.datastore:datastore-preferences:1.0.0-beta01"
}

Saving Data in DataStore:

class TodoPreferences(private val context: Context) {

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

companion object{
val LAST_EDITED_TODO = intPreferencesKey(name = "last_Edited_todo")
}

suspend fun saveEditedTodoId(id: Int){
context.dataStore.edit { preferences ->
preferences[ LAST_EDITED_TODO_KEY] = id
}
}

val lastEditedTodo: Flow<Int> = context.dataStore.data
.map { preferences ->
preferences[LAST_EDITED_TODO_KEY] ?: -1
}
}

Now in your ViewModel or whenever you want to save the todo id into the DataStore, you just need to call our suspend function saveEditedTodoId() from a kotlin coroutine.

class TodoViewModel(
private val repository: TodoRepository
) : ViewModel{
viewModelScope.launch {
musicPreferences.saveEditedTodoId(todo.id)
}
}

SharedPreferences vs. DataStore

Jetpack DataStore provides an asynchronous API for communicating with data, while SharedPreferences provides an async API only while reading the data from the Shared preferences using value-changed listeners.
DataStore is safe to call on the Main thread. It uses Dispatchers.IO for performing operations.
Jetpack DataStore does not throw runtime exceptions while storing or reading data, SharedPreferences can throw errors in runtime exceptions while parsing the data.
Proto DataStore provides better type safety.

SharedPreferences vs DataStore

Conclusion

The Jetpack DataStore comes up with lots of benefits and advantages higher than SharedPreferences like supporting coroutines, live data, and flows. It reads and writes the data asynchronously which means your call is safe on the Main thread and it also has error handling and signaling procedures, SharedPreferences has several drawbacks such as not being safe to call on the main thread and has an asynchronous API. DataStore is a better replacement for overcoming Sharedpreferences Drawbacks.

Need a consultation?

Drop us a line! We are here to answer your questions 24/7.