oblador / react-native-keychain

:key: Keychain Access for React Native
MIT License
3.12k stars 515 forks source link

[Android] Replace `SharedPreferences` with `DataStore` Preferences #629

Open ovitrif opened 3 months ago

ovitrif commented 3 months ago

Closes #628

This PR replaces the usage of SharedPreferences with DataStore.

Why

Google is recommending in their official documentation to migrate to DataStore from SharedPreferences, and they also provided a very easy-to-use auto-migration tool that will move the data to the new DataStore, then clean up the entries from SharedPreferences.

Their official guide for saving simple data with SharedPreferences displays an alert about this: Google Chrome 2024-03-14 001629

For security concerns as well, it is recommended to migrate to DataStore.

How

Since DataStore APIs are tailored for Kotlin, the code for using it is also done in Kotlin, thus introducing Kotlin to the project.

Calls to read and write to DataStore are forced to run synchronously based on the example provided by the Android team in Use DataStore in synchronous code.

Data Migration

SharedPreferencesMigration is used to migrate the entries stored in the RN_KEYCHAIN shared prefs file to data store. Upon completion, the SharedPreferences get removed.

Testing

There's an unit test added to check this, and I also tested it and it proved to work seamlessly in a React-Native app that is using this library, resulting in no data loss for the user or any issues when this gets upgraded.

Result

Before - SharedPreferences After - DataStore
Android Studio 2024-03-14 001625 Android Studio 2024-03-14 001625
ovitrif commented 3 months ago

@oblador Any idea why the error about compileSdkVersion is not specified. Please add it to build.gradle in the unit tests?

Could it be a side-effect of adding Kotlin?! 🤷🏻