There are few steps to implement dataStore in java base.
First and foremost, it is good to notice that there are 2 different types of dependencies for the datastore.
- TYPED datastore
- Preferences DataStore (SharedPreferences like APIs)
Here are some steps to implement the latter one in the java based application.
1. Implementation
// Preferences DataStore (SharedPreferences like APIs)
dependencies {
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha06"
// RxJava3 support
implementation "androidx.datastore:datastore-preferences-rxjava3:1.0.0-alpha06"
}
2. Create a Preferences DataStore
DataStore<Preferences> dataStore =
new RxPreferenceDataStoreBuilder(context, /*name=*/ "settings").build();
3. Write to a Preferences DataStore
Single<Preferences> updateResult = RxDataStore.updateDataAsync(dataStore,
prefsIn -> {
MutablePreferences mutablePreferences = prefsIn.toMutablePreferences();
Integer currentInt = prefsIn.get(INTEGER_KEY);
mutablePreferences.set(INTEGER_KEY, currentInt != null ? currentInt + 1 : 1);
return Single.just(mutablePreferences);
});
// The update is completed once updateResult is completed.
3. Read from a Preferences DataStore
Preferences.Key<Integer> EXAMPLE_COUNTER = PreferencesKeys.int("example_counter");
Flowable<Integer> exampleCounterFlow =
RxDataStore.data(dataStore).map(prefs -> prefs.get(EXAMPLE_COUNTER));
if you want to do more complex please checkout the full documentation
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…