You can use DataStore only in RxJava. In plain java you can use only SharedPreferences now. Let's compare RxJava DataStore Preferences with SharedPreferences
1) access
DataStore:
RxDataStore<Preferences> dataStore =
new RxPreferenceDataStoreBuilder(context, /*name=*/ "settings").build();
SharedPreferences:
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
2) read:
DataStore:
define a key for your value (in example for int value) and then access data of datastore : PreferencesKeys.int("example_counter")
datastore.data().map()
data()
- access the data of DataStore. This property returns a Flow
map()
- returns a Flow which contains the results of applying the given function to each value of the original Flow
SharedPreferences
sharedPref.getInt("highScoreKey", 0);
To retrieve values from a shared preferences file provide the key for the value you want with default value (o here in example)
3) write
DataStore:
dataStore.updateDataAsync()
transactionally update data in a DataStore
SharedPreferences:
Using SharedPreferences.Editor pass the keys and values you want to write with methods such as putInt() and putString(). Then call apply() or commit() to save the changes. Example
Conclusion: developer.android.com suggests consider migrating to DataStore instead of SharedPreferences. But while Java doesn't support DataStore, it's better to use SharedPreferences. if your application uses Kotlin or RxJava - it's better to use DataStore