DataStore Preferences
Replace SharedPreferences with the modern DataStore library. Read data as a Kotlin Flow, write with edit{}, and handle errors safely.
Why DataStore?
DataStore is the modern replacement for SharedPreferences. It solves real problems:
- SharedPreferences blocks the UI thread — DataStore is fully asynchronous
- SharedPreferences can throw uncaught exceptions — DataStore handles errors via Flow
- DataStore is type-safe (Preferences) or schema-safe (Proto)
- Works natively with Kotlin Coroutines and Flow
Two Types of DataStore
Choose the right type for your use case:
- Preferences DataStore — key-value pairs, no schema needed. Simplest to set up. Best for app settings, user preferences.
- Proto DataStore — typed objects using Protocol Buffers. Requires a .proto schema file. Best when you have structured data.
This lesson covers Preferences DataStore.