@@ -19,41 +19,19 @@ package com.codelab.android.datastore.data
19
19
import android.content.Context
20
20
import android.util.Log
21
21
import androidx.datastore.DataStore
22
- import androidx.datastore.DataStoreFactory
23
- import androidx.datastore.migrations.MigrationFromSharedPreferences
22
+ import androidx.datastore.createDataStore
24
23
import androidx.datastore.migrations.SharedPreferencesMigration
25
24
import androidx.datastore.migrations.SharedPreferencesView
26
25
import com.codelab.android.datastore.UserPreferences
27
26
import com.codelab.android.datastore.UserPreferences.SortOrder
28
27
import kotlinx.coroutines.flow.Flow
29
28
import kotlinx.coroutines.flow.catch
30
- import java.io.File
31
29
import java.io.IOException
32
30
33
31
private const val USER_PREFERENCES_NAME = " user_preferences"
34
32
private const val DATA_STORE_FILE_NAME = " user_prefs.pb"
35
33
private const val SORT_ORDER_KEY = " sort_order"
36
34
37
- // Define the mapping from SharedPreferences to UserPreferences
38
- private class UserPreferencesMigration : MigrationFromSharedPreferences <UserPreferences > {
39
- override suspend fun migrate (
40
- prefs : SharedPreferencesView ,
41
- currentData : UserPreferences
42
- ): UserPreferences {
43
- return if (currentData.sortOrder == SortOrder .UNSPECIFIED ) {
44
- currentData.toBuilder()
45
- .setSortOrder(
46
- SortOrder .valueOf(
47
- prefs.getString(SORT_ORDER_KEY , SortOrder .NONE .name) ? : SortOrder .NONE .name
48
- )
49
- )
50
- .build()
51
- } else {
52
- currentData
53
- }
54
- }
55
- }
56
-
57
35
/* *
58
36
* Class that handles saving and retrieving user preferences
59
37
*/
@@ -62,15 +40,26 @@ class UserPreferencesRepository private constructor(context: Context) {
62
40
private val TAG : String = " UserPreferencesRepo"
63
41
64
42
// Build the DataStore
65
- private val userPreferencesStore: DataStore <UserPreferences > = DataStoreFactory ().create (
66
- produceFile = { File (context.filesDir, DATA_STORE_FILE_NAME ) } ,
43
+ private val userPreferencesStore: DataStore <UserPreferences > = context.createDataStore (
44
+ fileName = DATA_STORE_FILE_NAME ,
67
45
serializer = UserPreferencesSerializer ,
68
- migrationProducers = listOf (
46
+ migrations = listOf (
69
47
SharedPreferencesMigration (
70
48
context,
71
- USER_PREFERENCES_NAME ,
72
- UserPreferencesMigration ()
73
- )
49
+ USER_PREFERENCES_NAME
50
+ ) { sharedPrefs: SharedPreferencesView , currentData: UserPreferences ->
51
+ // Define the mapping from SharedPreferences to UserPreferences
52
+ if (currentData.sortOrder == SortOrder .UNSPECIFIED ) {
53
+ currentData.toBuilder()
54
+ .setSortOrder(
55
+ SortOrder .valueOf(
56
+ sharedPrefs.getString(SORT_ORDER_KEY , SortOrder .NONE .name)!!
57
+ )
58
+ ).build()
59
+ } else {
60
+ currentData
61
+ }
62
+ }
74
63
)
75
64
)
76
65
0 commit comments