What were the issues with SharedPreferences?

  • Manually need to switch to a background thread
  • Cannot signal errors like IOException
  • They are not safe from runtime exception, it can throw parsing exception
  • Doesn’t have transactional API with strong consistency

All the above issues are now rectified with Preferences DataStore which under the hood uses kotlin flow and coroutines, that’s the reason now you can call save operation from the main thread and it will automatically switch the call to background thread by changing the context to IO thread.

What is Preferences DataStore?

It’s a replacement for the existing SharedPreferences where it offers more capabilities than the former. Also, it uses Kotlin flow so the data emitted from it are cold stream which means until somewhere data is collected it will not emit the stored value. The best of all is that as it uses Kotlin flow which can be used as liveData using asLiveData() so in this way, you can also make it lifecycle aware.

#kotlin #android-app-development #android #android-apps #androiddev

Preferences DataStore in a Kotlin Way
10.95 GEEK