The alternative of SharedPreferences is right here
What’s Jetpack DataStore?
In line with Android Improvement Docs, Jetpack DataStore is a knowledge storage answer that lets you retailer key-value pairs or typed objects with protocol buffers. DataStore makes use of Kotlin coroutines and Movement to retailer information asynchronously, constantly, and transactionally.
DataStore is a library from the Jetpack household that gives a brand new approach of easy information storage answer. It permits us to retailer information in key-value pairs similar to SharedPrefernces or within the typed objects. It’s constructed on Coroutines and Movement to retailer information asynchronously.
SharedPreferences vs DataStore
On this article, we’ll study Preferences DataStore.
What’s Preferences DataStore?
It shops information in key-value pairs like SharedPreferences. If you happen to already used SharedPreferences in previous then you’ll get a greater concept of the Preferences datastore.
To make use of the datastore, you could combine the library into the app-level
It’s secure now. You should use this in your challenge stress-free😁.
It’s time to jot down some code
My private favourite characteristic of Kotlin is its extension perform. We will lengthen any perform we need to. For Preferences information retailer, I’ve prolonged
Context class from saving to retrieving the information.
DataStore , we have to create one helper utils file and for that objective, you simply want to make use of the snippet code. It comprises all type-value. A ready-to-go code for each challenge.
When you accomplished the above step, now you could name these features within the
ViewModel class. Whereas writing any information to the information retailer it’s
droop perform and it must name from the
Within the instance to grasp the information retailer, we’ll retailer
String sort information and likewise retrieve the identical information sort.
In an effort to save the string information into the information retailer, you simply have to name
saveNameUser(title:String) perform into your Exercise/Fragment.
To retrieve the information we have to observe
getUserName LiveData variable in our Exercise/Fragment. As quickly as information adjustments, UI is up to date instantly by utilizing the LiveData.
Now, every time we replace the worth of the information retailer it’s going to observe every time and the textual content view will likely be up to date accordingly.
That’s all! Hope you discovered one thing. In case of any doubt, simply remark! I’ll joyful to resolve your points. I hope you’ll use
DataStore as an alternative of
SharedPrefernces from the present tasks to all new tasks.
Thanks and Cheers!