SharedPreferencesMigration

public final class SharedPreferencesMigration<T extends Object> implements DataMigration


DataMigration instance for migrating from SharedPreferences to DataStore.

Summary

Public constructors

<T extends Object> SharedPreferencesMigration(
    Function0<SharedPreferences> produceSharedPreferences,
    Set<String> keysToMigrate,
    SuspendFunction1<T, Boolean> shouldRunMigration,
    SuspendFunction2<SharedPreferencesView, T, T> migrate
)

DataMigration from SharedPreferences to DataStore.

<T extends Object> SharedPreferencesMigration(
    Context context,
    String sharedPreferencesName,
    Set<String> keysToMigrate,
    SuspendFunction1<T, Boolean> shouldRunMigration,
    SuspendFunction2<SharedPreferencesView, T, T> migrate
)

DataMigration from SharedPreferences to DataStore.

Public methods

void

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

@NonNull T
migrate(T currentData)

Perform the migration.

boolean
shouldMigrate(T currentData)

Return whether this migration needs to be performed.

Public constructors

SharedPreferencesMigration

public final <T extends Object> SharedPreferencesMigration(
    Function0<SharedPreferences> produceSharedPreferences,
    Set<String> keysToMigrate,
    SuspendFunction1<T, Boolean> shouldRunMigration,
    SuspendFunction2<SharedPreferencesView, T, T> migrate
)

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
Function0<SharedPreferences> produceSharedPreferences

Should return the instance of SharedPreferences to migrate from.

Set<String> keysToMigrate

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 not set, all keys will be migrated from the existing SharedPreferences.

SuspendFunction2<SharedPreferen