Updated 2 February 2021
This is time to say bye bye to SharePreferences. Jetpack DataStore is new solution to store data. It is replacement of SharePreferences. Preferences DataStore is one way of DataStore to save data.
In share preference, we can only save data in key-value. It allows us to store data in key-value pair and in form of object as well.
It saves data using Async Api and it builds with coroutines and flow.
DataStore provides two different implementations :
In this blog, we will cover Preferences DataStore only.
1 |
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha06" |
Now, create a instance of datastore. It will create a file name as “MyDataStore”.
“createDataStore” is a extension function created on Context. Method will return DataStore instance.
1 2 3 |
val dataStore: DataStore<Preferences> = createDataStore( name = "MyDataStore" ) |
To save the data, first we need to create a key for our value.
1 |
val CUSTOMER_NAME = stringPreferencesKey("customer_name") |
This will define the name of key and it’s type.
If you wanna save int value, you will have to use ‘intPreferencesKey‘.
1 2 3 4 5 |
suspend fun saveData() { dataStore.edit {dataStore-> dataStore[CUSTOMER_NAME] = "Ayushi" } } |
‘edit‘ method is used to save data in DataStore. It is suspend function. It should be called by either coroutines or another suspend function.
Call a suspend function :
1 2 3 |
GlobalScope.launch { saveData() } |
We use Global scope to create coroutines.
Check following link for kotlin coroutines : Kotlin Coroutines
1 2 |
var obj : Flow<String> = dataStore.data .map { preferences -> preferences[CUSTOMER_NAME] ?: "" } |
DataStores provides data property to expose the value.
We create string type flow object.
Flow :
1 |
An asynchronous data stream that sequentially emits values and completes normally or with an exception. |
To learn more about flow, check following link : Kotlin Flow
Hopefully, this blog will be helpful for you.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.