At 1:14 am today, Google’s Android developer official tweeted the alpha version of Jetpack DataStore. Jetpack DataStore is a new data storage solution designed to replace SharedPreferences.

a new and improved data storage solution aimed at replacing SharedPreferences.

Jetpack DataStore is based on Kotlin coroutines and Flow and provides two formal implementations. One is Proto DataStore and the other is Preferences DataStore. The former stores typed objects and the latter stores key-value pairs (similar to SharedPreferences).

Since I have not been exposed to Protocol Buffers, the following initial use will not involve Proto DataStore. Read the reference documentation if necessary.

Comparison of data storage schemes

0 references

/ / enable JDK8
android{
    kotlinOptions {
        jvmTarget = '1.8'}}// Preferences DataStore
implementation "Androidx. Datastore: datastore - preferences: 1.0.0 - alpha01"


// Proto DataStore(ensure that proTO-related dependencies are referenced)
implementation  "Androidx. Datastore: datastore - core: 1.0.0 - alpha01"

Copy the code

1 create the DataStore

	val dataStore: DataStore<Preferences> = context.createDataStore(
    	name = "settings"
	)
Copy the code

Name is user-defined. Datastores are automatically created when data is written for the first time. Preferences_pb file in data/data/< package name >/files/{preferences_pb}

2 set the key

	private val key = preferencesKey<Int>(name = "my_counter")
Copy the code
  • The Key type can only beInt, Long, Boolean, Float, String
  • Name is the name of the key

3 write data

	// Add the value of the DataStore and store it again
	private suspend fun incrementCounter(a) {
        dataStore.edit { settings ->
            valcurrentCounterValue = settings[key] ? :0
            settings[key] = currentCounterValue + 1
        }
    }
    
    btn_write.setOnClickListener {
        lifecycleScope.launch(Dispatchers.IO) {
            incrementCounter()
        }
    }
Copy the code

4 read data

	private val myCounterFlow: Flow<Int> =
        dataStore.data.map { currentPreferences -> currentPreferences[key] ? :0 }
        
	btn_read.setOnClickListener {
            lifecycleScope.launch(Dispatchers.IO) {
                myCounterFlow.collectLatest {
                    withContext(Dispatchers.Main) {
                        Toast.makeText(this@MainActivity."$it", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

Copy the code

5 Merge the SharedPreferences to the DataStore

    private val dataStore: DataStore<Preferences> = createDataStore(
        "settings",
        migrations = listOf(SharedPreferencesMigration(this."sp")))Copy the code

Pass in a migrations parameters, receive a SharedPreferencesMigration list.

— — — —

Keep it simple and your code will run. Read the documentation and source code in detail