Google Florina Muntenescu and Rohit Sathyanarayana Sep 2, 2020

Data Storage Best Practices with Jetpack

M9 Related OWASP risk: Insecure Data Storage Learn more →

Article Summary

Florina Muntenescu and Rohit Sathyanarayana from Google reveal why SharedPreferences has been secretly blocking your UI thread and causing ANRs. Their solution? Jetpack DataStore, a complete reimagining of Android data storage.

The Android team introduces DataStore, a Kotlin coroutines and Flow-based replacement for SharedPreferences. The article breaks down two implementations (Proto and Preferences), compares them against legacy options, and provides migration guidance for existing apps.

Key Takeaways

Critical Insight

DataStore replaces SharedPreferences with a fully asynchronous, type-safe storage solution that eliminates UI thread blocking and provides transactional data consistency.

The article includes specific code examples showing how Proto DataStore's schema generation creates compile-time safety that Preferences DataStore can't match.

About This Article

Problem

SharedPreferences can throw runtime exceptions when parsing fails, and there's no built-in error handling. The synchronous API also doesn't support transactions, which means data can get corrupted if multiple threads access it at the same time.

Solution

Google's DataStore team built a suspending updateData() function that handles read-write-modify operations as atomic transactions. Data gets written to disk before the coroutine finishes, so race conditions can't happen.

Impact

DataStore prevents parsing errors by using strongly typed Protocol Buffer schemas. Transactions guarantee that data stays consistent, and the Flow-based API runs all operations on Dispatchers.IO so the UI thread never gets blocked.