Skip to content

Commit 02a54eb

Browse files
rohitsat13florina-muntenescu
authored andcommitted
Modify the DataStore sample app to work with the new Preferences API.
1 parent 16c1a1b commit 02a54eb

File tree

1 file changed

+29
-44
lines changed

1 file changed

+29
-44
lines changed

app/src/main/java/com/codelab/android/datastore/data/UserPreferencesRepository.kt

Lines changed: 29 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,13 @@ package com.codelab.android.datastore.data
1919
import android.content.Context
2020
import android.util.Log
2121
import androidx.datastore.DataStore
22-
import androidx.datastore.preferences.PreferenceDataStoreFactory
23-
import androidx.datastore.preferences.Preferences
24-
import androidx.datastore.preferences.SharedPreferencesMigration
22+
import androidx.datastore.preferences.*
2523
import kotlinx.coroutines.flow.Flow
2624
import kotlinx.coroutines.flow.catch
2725
import kotlinx.coroutines.flow.map
28-
import java.io.File
2926
import java.io.IOException
3027

3128
private const val USER_PREFERENCES_NAME = "user_preferences"
32-
private const val USER_PREFERENCES_STORE_FILE_NAME = "user.preferences_pb"
33-
private const val SORT_ORDER_KEY = "sort_order"
34-
private const val SHOW_COMPLETED_KEY = "show_completed"
3529

3630
enum class SortOrder {
3731
NONE,
@@ -41,24 +35,10 @@ enum class SortOrder {
4135
}
4236

4337
data class UserPreferences(
44-
val showCompleted: Boolean,
38+
val showCompleted: Boolean = false,
4539
val sortOrder: SortOrder
4640
)
4741

48-
/**
49-
* Extension function on Preferences to easily get the sort order
50-
*/
51-
private fun Preferences.getSortOrder(): SortOrder {
52-
val order = getString(SORT_ORDER_KEY, SortOrder.NONE.name)
53-
return SortOrder.valueOf(order)
54-
}
55-
56-
/**
57-
* Extension function on Preferences to easily set the sort order
58-
*/
59-
private fun Preferences.withSortOrder(newSortOrder: SortOrder) =
60-
this.toBuilder().setString(SORT_ORDER_KEY, newSortOrder.name).build()
61-
6242
/**
6343
* Class that handles saving and retrieving user preferences
6444
*/
@@ -67,19 +47,17 @@ class UserPreferencesRepository private constructor(context: Context) {
6747
private val TAG: String = "UserPreferencesRepo"
6848

6949
private val dataStore: DataStore<Preferences> by lazy {
70-
PreferenceDataStoreFactory().create(
71-
produceFile = {
72-
File(
73-
context.applicationContext.filesDir,
74-
USER_PREFERENCES_STORE_FILE_NAME
75-
)
76-
},
77-
// Since we're migrating from SharedPreferences, add a migration based on the
78-
// SharedPreferences name
79-
migrationProducers = listOf(SharedPreferencesMigration(context, USER_PREFERENCES_NAME))
50+
context.createDataStore(
51+
name = USER_PREFERENCES_NAME,
52+
migrations = listOf(SharedPreferencesMigration(context, USER_PREFERENCES_NAME))
8053
)
8154
}
8255

56+
private object Keys {
57+
internal val SORT_ORDER_KEY = preferencesKey<String>("sort_order")
58+
internal val SHOW_COMPLETED_KEY = preferencesKey<Boolean>("show_completed")
59+
}
60+
8361
/**
8462
* Get the user preferences flow.
8563
*/
@@ -88,14 +66,17 @@ class UserPreferencesRepository private constructor(context: Context) {
8866
// dataStore.data throws an IOException when an error is encountered when reading data
8967
if (exception is IOException) {
9068
Log.e(TAG, "Error reading preferences.", exception)
91-
emit(Preferences.empty())
69+
emit(emptyPreferences())
9270
} else {
9371
throw exception
9472
}
9573
}.map { preferences ->
9674
// Get the sort order from preferences and convert it to a [SortOrder] object
97-
val sortOrder = preferences.getSortOrder()
98-
val showCompleted = preferences.getBoolean(SHOW_COMPLETED_KEY, false)
75+
val sortOrder =
76+
SortOrder.valueOf(
77+
preferences[Keys.SORT_ORDER_KEY] ?: SortOrder.NONE.name
78+
)
79+
val showCompleted = preferences[Keys.SHOW_COMPLETED_KEY] ?: false
9980
UserPreferences(showCompleted, sortOrder)
10081
}
10182

@@ -105,9 +86,10 @@ class UserPreferencesRepository private constructor(context: Context) {
10586
suspend fun enableSortByDeadline(enable: Boolean) {
10687
// updateData handles data transactionally, ensuring that if the sort is updated at the same
10788
// time from another thread, we won't have conflicts
108-
dataStore.updateData { currentPreferences ->
109-
val currentOrder = currentPreferences.getSortOrder()
110-
val newSortOrder =
89+
dataStore.edit { prefs ->
90+
val currentOrder = prefs[Keys.SORT_ORDER_KEY]?.let { SortOrder.valueOf(it) }
91+
92+
val newSortOrder =
11193
if (enable) {
11294
if (currentOrder == SortOrder.BY_PRIORITY) {
11395
SortOrder.BY_DEADLINE_AND_PRIORITY
@@ -121,7 +103,8 @@ class UserPreferencesRepository private constructor(context: Context) {
121103
SortOrder.NONE
122104
}
123105
}
124-
currentPreferences.withSortOrder(newSortOrder)
106+
107+
prefs[Keys.SORT_ORDER_KEY] = newSortOrder.name
125108
}
126109
}
127110

@@ -131,8 +114,9 @@ class UserPreferencesRepository private constructor(context: Context) {
131114
suspend fun enableSortByPriority(enable: Boolean) {
132115
// updateData handles data transactionally, ensuring that if the sort is updated at the same
133116
// time from another thread, we won't have conflicts
134-
dataStore.updateData { currentPreferences ->
135-
val currentOrder = currentPreferences.getSortOrder()
117+
dataStore.edit { prefs ->
118+
val currentOrder = prefs[Keys.SORT_ORDER_KEY]?.let { SortOrder.valueOf(it) }
119+
136120
val newSortOrder =
137121
if (enable) {
138122
if (currentOrder == SortOrder.BY_DEADLINE) {
@@ -147,13 +131,14 @@ class UserPreferencesRepository private constructor(context: Context) {
147131
SortOrder.NONE
148132
}
149133
}
150-
currentPreferences.withSortOrder(newSortOrder)
134+
135+
prefs[Keys.SORT_ORDER_KEY] = newSortOrder.name
151136
}
152137
}
153138

154139
suspend fun updateShowCompleted(showCompleted: Boolean) {
155-
dataStore.updateData { currentPreferences ->
156-
currentPreferences.toBuilder().setBoolean(SHOW_COMPLETED_KEY, showCompleted).build()
140+
dataStore.edit { prefs ->
141+
prefs[Keys.SHOW_COMPLETED_KEY] = showCompleted
157142
}
158143
}
159144

0 commit comments

Comments
 (0)