Android 12 Developer Preview is here! Try it out, and give us your feedback!

SharedPreferencesMigration

class SharedPreferencesMigration<T> : DataMigration<T>
kotlin.Any
   ↳ androidx.datastore.migrations.SharedPreferencesMigration

DataMigration instance for migrating from SharedPreferences to DataStore.

Summary

Public constructors
<init>(produceSharedPreferences: () -> SharedPreferences, keysToMigrate: Set<String>? = MIGRATE_ALL_KEYS, shouldRunMigration: suspend (T) -> Boolean = { true }, migrate: suspend (SharedPreferencesView, T) -> T)

DataMigration from SharedPreferences to DataStore.

<init>(context: Context, sharedPreferencesName: String, keysToMigrate: Set<String>? = MIGRATE_ALL_KEYS, shouldRunMigration: suspend (T) -> Boolean = { true }, migrate: suspend (SharedPreferencesView, T) -> T)

DataMigration from SharedPreferences to DataStore.

Public methods
suspend Unit

Clean up any old state/data that was migrated into the DataStore.

suspend T
migrate(currentData: T)

Perform the migration.

suspend Boolean
shouldMigrate(currentData: T)

Return whether this migration needs to be performed.

Public constructors

<init>

SharedPreferencesMigration(
    produceSharedPreferences: () -> SharedPreferences,
    keysToMigrate: Set<String>? = MIGRATE_ALL_KEYS,
    shouldRunMigration: suspend (T) -> Boolean = { true },
    migrate: suspend (SharedPreferencesView, T) -> T)

DataMigration from SharedPreferences to DataStore.

Note: This migration only supports the basic SharedPreferences types: boolean, float, int, long, string and string set. If the result of getAll contains other types, they will be ignored.

Example usage:

val sharedPrefsMigration = SharedPreferencesMigration(
  produceSharedPreferences = { EncryptedSharedPreferences.create(...) }
) { prefs: SharedPreferencesView, myData: MyData ->
   myData.toBuilder().setCounter(prefs.getCounter(COUNTER_KEY, default = 0)).build()
}
Parameters
produceSharedPreferences: () -> SharedPreferences Should return the instance of SharedPreferences to migrate from.
keysToMigrate: Set<String>? = MIGRATE_ALL_KEYS The list of keys to migrate. The keys will be mapped to datastore .Preferences with their same values. If the key is already present in the new Preferences, the key will not be migrated again. If the key is not present in the SharedPreferences it will not be migrated. If keysToMigrate is null, all keys will be migrated from the existing SharedPreferences.
migrate: suspend (SharedPreferencesView, T) -> T maps SharedPreferences into T. Implementations should be idempotent since this may be called multiple times. See DataMigration.migrate for more information. The lambda accepts a SharedPreferencesView which is the view of the SharedPreferences to migrate from (limited to keysToMigrate and a T which represent the current data. The function must return the migrated data.

<init>

SharedPreferencesMigration(
    context: Context,
    sharedPreferencesName: String,
    keysToMigrate: Se