Reputation: 1023
Performing a migration from SharedPrefs into DataStore is straightforward and documented very well. However when I want to do a simple "version bump" migration from DataStore to still DataStore, meaning some keys might have changed etc. how should one do that?
As far as I see now, we need to manually implement these functions in the migrations parameter when creating the DataStore.
PreferenceDataStoreFactory.create(
migrations = listOf(
object : DataMigration<Preferences> {
override suspend fun cleanUp() {
TODO("Not yet implemented")
}
override suspend fun migrate(currentData: Preferences): Preferences {
TODO("Not yet implemented")
}
override suspend fun shouldMigrate(currentData: Preferences): Boolean {
TODO("Not yet implemented")
}
},
),
produceFile = {
get<Context>().preferencesDataStoreFile("filename")
}
)
I haven't seen anyone talking about it, or it being part of the codelab unfortunately which was a big surprise to me. Could someone point me to where I could look to get some inspiration about how to do this properly?
Upvotes: 11
Views: 1730
Reputation: 2980
You need to manually implement the DataMigration
interface.
There is a very well written step-by-step article about this: https://medium.com/androiddevelopers/datastore-and-data-migration-fdca806eb1aa
Upvotes: 0
Reputation: 93
do you want the complete tutorial or just want to know what should be done on this functions i am giving this suggestion Is it useful for you
object : DataMigration<Preferences> {
override suspend fun cleanUp() {
//Delete any data that is no longer needed
}
override suspend fun migrate(currentData: Preferences): Preferences {
//Update the data based on the current version and desired version
return currentData
}
override suspend fun shouldMigrate(currentData: Preferences): Boolean {
//Check the current version and compare it to the desired version
return currentData.version < desiredVersion
}
}
Upvotes: 1