Search code examples
androidkotlinandroid-preferencesandroid-jetpackandroid-jetpack-datastore

How to delete the preference file created by Jetpack DataStore


I have a multi-user application and use DataStore to create a preference file for each user. I want to be able to delete the file that is created by DataStore once the user unregisters. I found this question but it only clears the preferences within the file. Since the application might have multiple users it would be better to delete the whole file. How can this be done?


Solution

  • Since DataStore doesn't seem to provide a way to delete the files, I decided to delete it myself.

    companion object {
        private const val DATASTORE_PATH = "datastore/"
        private const val PREFERENCE_EXTENSION = ".preferences_pb"
    }
    
    fun deletePreferenceFile(userId: String) {
        val file = File(context.filesDir, "$DATASTORE_PATH$userId$PREFERENCE_EXTENSION")
        file.delete()
    }