Skip to content

Data Store

Devrath edited this page May 1, 2021 · 2 revisions

What is Data Store

  • Datastore is a component of data storage solution from the android jetpack.
  • It allows us to store the key/value pairs like shared preferences or typed objects with protocol buffers.
  • Data store uses kotlin, coroutines, and flow to store data asynchronously with consistency and transaction support

Why use datastore when we already have shared preferences

  • Shared Preferences are synchronous and not main thread-safe, But data store is safe to use in the main thread since it uses Dispatchers.IO under the hood.
  • Shared Preferences are not safe from runtime exceptions, But the Data-Store is safe from runtime exceptions
  • There is an easy way to migrate from Shared Preferences

Type of Data Store

Preference Data Store Proto Data Store

Demo represents how the data-store is used

  • Here we have a fragment where we are storing a value entered in edit-text, on click of save button, We have used global scope here
  • We are displaying the data from the dataManager helper class that gets the data from the data store via a flow and displays the data in the text view
  • View <->ManagerClass