Preferences DataStore is ideal for small, simple datasets, such as storing login details, the dark mode setting etc. The DataStore is not suitable for complex datasets. If you need to store large or complex datasets, use Room instead.
Preferences DataStore accesses and stores data based on key-value pairs, without defining a schema (database model) upfront.
LAYOUT_PREFERENCES_NAME is the name of the instantiated Preferences DataStore.
The DataStore instance is created using the preferencesDataStore delegate. Since you are using Preferences Datastore, you need to pass Preferences as a datastore type.
💡 Create the DataStore instance at the top level of your Kotlin file once, and access it through this property throughout the rest of your application. This makes it easier to keep your DataStore as a singleton.
Preferences DataStore does not use a predefined schema. It uses corresponding key type functions to define a key for each value that you store in the DataStore<Preferences> instance, e.g., to define a key for an int value, use intPreferencesKey(), and for a string value use stringPreferencesKey(). In general, these function names are prefixed with the type of data you want to store against the key.
Preferences DataStore provides an edit() suspend function that transactionally updates the data in DataStore. The function's transform parameter accepts a block of code where you can update the values as needed. All of the code in the transform block is treated as a single transaction.
Preferences DataStore exposes the data stored in a Flow<Preferences> that emits every time a preference has changed. You don't want to expose the entire Preferences object, just the Boolean value. To do this, we map the Flow<Preferences>, and get the Boolean value you're interested in.
As DataStore reads and writes data from files, IOExceptions may occur when accessing the data, therefore .catch.
Since the Datastore is empty on the first run, return true by default.