As the Android lead moving a shipped app from SharedPreferences to DataStore, how would you plan the migration and choose Preferences or typed DataStore as the team default?
answer
- produceMigrations on the delegate
- same key names, same types
- existing DataStore keys win
- cleanUp deletes the old keys
- rollback and every reader at once
basics
~20 sRegister a SharedPreferencesMigration in produceMigrations, keep key names and types identical, switch every reader in the same release because cleanUp deletes the old keys, and plan for rollback. Default to Preferences DataStore for flat settings, typed DataStore for structured objects.
solid answer
~40 sMechanically, `SharedPreferencesMigration(context, "reader_prefs")` goes into the delegate's `produceMigrations`. It runs before any read or update completes, copies boolean, float, int, long, string and string-set values under the same names, skips keys already in DataStore, and then `cleanUp` removes the migrated keys (all of them by default), deleting the emptied file when built from a context and name. So every reader and writer must switch in that release, old builds lose the values on downgrade, and the DataStore keys must match the old names and types. For a typed store, the generic constructor maps a `SharedPreferencesView` into your object. As a default I'd use Preferences DataStore for small flat settings and the straight migration, and typed DataStore with a `Serializer` for structured data that changes together, accepting codegen and schema discipline.
code
kotlin · 26 linesimport android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
private const val LEGACY_PREFS = "reader_prefs"
// Same names and types the old code used with putString / putInt.
val THEME = stringPreferencesKey("theme")
val FONT_SIZE = intPreferencesKey("font_size")
val Context.readerSettings: DataStore<Preferences> by preferencesDataStore(
name = "reader_settings",
produceMigrations = { context ->
listOf(
SharedPreferencesMigration(
context = context,
sharedPreferencesName = LEGACY_PREFS,
keysToMigrate = setOf("theme", "font_size"),
)
)
},
)go deeper
Recall that SharedPreferencesMigration is registered through produceMigrations and copies keys under the same names before the first read.
Explain the mechanics: existing DataStore keys win, keysToMigrate limits scope, cleanUp deletes the migrated keys, and failures retry on the next access.
Plan the release: matching names and types, every reader switched at once, startup cost of the first read, and tests with a pre-populated file.
Own the tradeoffs: reversibility against cleanUp, how long the migration stays, and the Preferences-versus-typed default with the cost each puts on the team.
## What the library gives you DataStore ships the migration as a **`DataMigration`**. For Preferences DataStore it is the `SharedPreferencesMigration(context, sharedPreferencesName, keysToMigrate)` function; for a typed store it is the generic `SharedPreferencesMigration<T>` class, whose `migrate` lambda maps a read-only `SharedPreferencesView` and the current value into a new value. You register it through `produceMigrations` on the delegate, which receives the application context. What it does, as written in the source: - **When:** migrations run **before any access to data** completes. The first `data` read or `updateData` waits for them, inside one transaction. - **What:** the Preferences version copies `Boolean`, `Float`, `Int`, `Long`, `String` and `Set<String>` values under the **same key names**; other types in `getAll()` are ignored. - **Conflicts:** a key **already present** in DataStore is not overwritten. - **Scope:** `keysToMigrate` limits the migration to named keys; by default it takes all of them. It does not run if the `SharedPreferences` are empty or hold none of the listed keys. - **Afterwards:** `cleanUp` **removes the migrated keys** from `SharedPreferences` (every key when no `keysToMigrate` was given), and when the migration was built from a context and a name, deletes the file if it is now empty. - **Retries:** if the migration or the write fails, nothing is committed and the next access tries again, so a custom `migrate` must be idempotent. ## The plan 1. **Inventory the keys.** List every `SharedPreferences` file, key name and the type it was written with. Define DataStore keys with the **same names and types**; a key written with `putInt` and read through `longPreferencesKey` fails with a `ClassCastException`. 2. **One store per concern.** Map each old file to a DataStore file, or merge them with one migration per source file. 3. **Switch every reader and writer in the same release.** Because `cleanUp` deletes the old keys, any code still reading `SharedPreferences`, including a library, sees defaults from then on, and change listeners stop hearing about those settings. 4. **Decide on rollback.** A downgrade to a build that reads `SharedPreferences` finds the keys gone. If the release must stay reversible, ship a first release with a custom `DataMigration` whose `cleanUp` leaves the old file, and delete it a release later. 5. **Keep the migration in place for several releases.** Users skip versions; `shouldMigrate` is cheap when the old file is empty or gone. 6. **Watch startup.** The first read now includes the migration. Do not wrap it in `runBlocking` on the main thread; start the read asynchronously early. 7. **Test it** with a pre-populated `SharedPreferences` file: values arrive, existing DataStore values win, and the old keys are removed. ## Choosing the team default | | Preferences DataStore | Typed DataStore (Proto or JSON) | |---|---|---| | Fit | Small, flat settings | One structured object with nested fields | | Migration from SharedPreferences | Keys map one to one | Write a mapping lambda | | Type safety | Runtime, through key types | Compile time, through `T` | | Cost | Almost none | A `Serializer`, codegen for Proto, schema discipline | A reasonable default: **Preferences DataStore** for app settings such as theme and font size, because it migrates directly and needs no schema; **typed DataStore** where a value is a coherent object, such as a user profile, because fields update together in one `updateData` and the compiler checks every access. Either way, each update rewrites the whole file, so keep files small and split by concern. ## What stays out of DataStore - Large or relational data goes to a database; a store that grows past a few dozen values or needs queries is a sign the data was never settings. - Credentials and secrets belong to the secure storage design, not to a plain DataStore file. - DataStore files live under `files/datastore/` and are included in Android Auto Backup by default, so decide per file what should leave the device. ## How to present it Lead with the risk, which is losing a user's settings or splitting them across two stores, then the mechanics that control it: same names and types, existing values win, `cleanUp` deletes, every reader switches at once. Close with the default and the cost the team accepts with it.
- How do you migrate SharedPreferences into a typed DataStore instead?Use the generic `SharedPreferencesMigration<T>(context, name) { prefs, current -> ... }` from the core artifact. The lambda receives a read-only `SharedPreferencesView`, with `getString`, `getInt` and the other getters, plus the current value, and returns the new object, for example `current.copy(displayName = prefs.getString("display_name") ?: current.displayName)`. It must be idempotent because it can run more than once.
- A release with the migration crashes and you roll back; what do users see?Users who already ran it have their values in DataStore and the migrated keys removed from SharedPreferences, so the old build shows defaults. To keep rollback safe, ship a custom `DataMigration` whose `cleanUp` leaves the old file for one release, then remove the legacy file once the new build is stable.
- SharedPreferencesMigration keeps the old keys, so old and new code can run side by side.
- The SharedPreferences value always overwrites what DataStore already holds.
- Keys can be renamed during the Preferences migration without extra code.
- The migration runs in the background after the app has started reading.
- Proto DataStore should be the default for every setting, however small.