Search code examples
javaandroidkotlindatastoreandroid-jetpack-datastore

How to implement Datastore in java based android app?


I can only find ways to implement datastore through Kotlin. I have tried creating it with DataStore<Preferences> datastore = new Datastore<Preferences> but as soon as proceed with it, it overrides to methods namely save and loadData but the parameters passed in them are also in Kotlin. Should I proceed with Sharedpreferences only?


Solution

  • 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.

    1. TYPED datastore
    2. 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