Loading...
Home
  • Tech Blogs
  • Videos
  • Conferences
    • Droidcon News
    • Upcoming Conferences
    • Become a Partner
    • Past Events
    • Keep Me Informed
    • Diversity Scholarships
  • Community
    • droidcon Team
    • How to Hold a Droidcon
  • Android Careers
Sign In

Global CSS

 

Let’s Explore Jetpack DataStore

In this article we will learn about DataStore which is a new data storage solution in Android Jetpack.

 

 
vivek singh
I like to code.
Published: September 11, 2020
Tweet
Share
 

Image Source: Android Jetpack official page

 

Ever since the release of Android Jetpack it has come up with several libraries which makes us writing better Android code, avoid boilerplate code, etc. and now this time it has brought us an another awesome library called DataStore which according to official blog aims to replace the SharedPreferences API which has several drawbacks.

DataStore is a storage solution which is built on Coroutines and Flow to store data asynchronously. DataStore allows us to either store data in key-value pairs much like SharedPreferences or in typed objects which are backed by protocol buffers.


SharedPreferences vs. DataStore

  • DataStore provides asynchronous API for storing and reading data, while SharedPreferences provides async API only while reading changed values with the use of listeners.
  • DataStore is safe to call on the UI thread. It uses Dispatchers.IO under the hood.
  • DataStore is safe from runtime exceptions, while SharedPreferencescan throw parsing errors in runtime exceptions.
  • Proto DataStore provides better type safety out of the box.

 

Image for post

Image Source: Android Developers Blog
 

 


Types of DataStore

Jetpack provides two implementations of DataStore:

  • Preferences DataStore— It stores data in a key-value pairs like SharedPreferences but does not provide any type safety.
  • Proto DataStore — It store data as custom objects. It provides type safety out of the box, but it requires you to specify a scheme using protocol buffers.

In this article we will learn about the Preferences DataStore.


Setup Your Project

As working with any library, first you need to add a dependency in your app level build.gradle file.

 

dependencies {
    // Preferences DataStore
    implementation "androidx.datastore:datastore-preferences:1.0.0-alpha01"
}

 

Currently, the DataStore library is in the alpha stage, but you can always get the latest version from the official docs.

Saving Data in DataStore

Suppose you are creating a music application and you want to save the id of the last music played by the user, so that the user can find the last played song when he opens the app again after some time.

For this, we will create a class MusicPreferences where we will handle all the preferences set by the user.

 

 

MusicPreferences.kt

 

  • The MusicPreferences class will require the Context object to create the DataStore.
  • We can create our DataStore with the .createDataStore() extension function of the Context object. We need to set the name of our datastore with the mandatory name parameter.
  • You need to define a key for each value to save with the Preferences.preferencesKey() function. You also need to define the name of the key with name parameter.
  • We can create a function to save the song id in the DataStore. The DataStore provides a edit() method to save the value. We can pass the key and value to the MutablePreferences in the trailing lambda. Note that the edit() function is a suspend function.
  • Now you can get the saved preferences from the datastore with datastore.data which returns a Flow<Preferences> and with the .map{} operator we can can get the Flow<Int> which is our song id by passing the right key into the preferences.

Now in your ViewModel or activity/fragment whenever you want to save the song id into the DataStore, you just need to call our suspend function saveLastPlayedSongID() from a coroutine.

 

 

MusicViewModel.kt

 

In order to get the saved song id in the activity from the DataStore we can change the get the Flow<Int> and observe it after changing to LiveData with .asLiveData().

 

 

 

Now, as we have exposed the song id as a Flow, it will emit the values each time the song id is updated or edited in the datastore and the last played song will be updated accordingly.


Conclusion

The DataStore library comes up with many benefits over the SharedPreferences API such as supporting coroutines and flows. It reads and writes the data asynchronously which makes it safe to call on the UI thread and it also has an error signalling mechanism, whereas SharedPreferences has several drawbacks such as not safe to call on the UI thread and has an asynchronous API. DataStore is an excellent replacement that solves most of the problems with SharedPreferences.


 

References

  • Android Developers Blog
  • Official Docs

 

 

Tags: Android, Android App Development, Jetpack, Kotlin, AndroidDev

 

 

View original article at: 


 

Originally published: September 09, 2020

Android News
Getting… your BottomSheetScaffold working on Jetpack Compose Beta 03
Getting… your BottomSheetScaffold working on Jetpack Compose Beta 03

By Carlos Mota

It’s Monday, no releases this week, and… there’s a new version of Jetpack Compose — beta 03—available. What a perfect time to just increment 02 to 03 and see what’s new. The API is (almost) final so after updating from alpha to beta there weren’t any big changes to do. However, and remember that’s still in development, there’s always something that I need to update. 

By ProAndroidDev -
Android News
Noisy Code 🗣 With Kotlin Scopes
Noisy Code 🗣 With Kotlin Scopes

By Chetan Gupta

Scopes make your code more readable? think again... You are going to encounter these scope functions namely let, run, apply, also, within every Kotlin codebase, along with all the mischievous ways developers exploit their usage from the way they were intended for. Let see how popular opinion on those ends up just as a code noise.

By ProAndroidDev -
Android News
Improving Android DataBinding with Bindables library
Improving Android DataBinding with Bindables library

By Jaewoong Eum

DataBinding is one of the most important factors for MVVM architecture. The basic concept of DataBinding is to link the view and view model via observer patterns, properties, event callbacks, etc. Linking and automating communication between the view via the bound properties or something in the view model has a lot of benefits in the MVVM architecture concept.

By ProAndroidDev -
Android News
KMM QuickStart Guide
KMM QuickStart Guide

By Mayank Kharbanda

Kotlin Multiplatform (KMP) is a code-sharing technology that allows us to use the same code for different platforms whether it’s JVM, Android, iOS, watchOS, tvOS, Web, Desktop, or WebAssembly. In this article, we will use Kotlin Multiplatform Mobile (KMM) which is a subset of KMP with the focus on providing better tooling and support for sharing code on mobile platforms i.e. Android and iOS.

By ProAndroidDev -
droidcon News

Tech Showcases,

Developer Resources &

Partners

/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/home-details/EmployerBrandingHeader
EmployerBrandingHeader
https://jobs.droidcon.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/jobs-droidcon/jobs.droidcon.com
jobs.droidcon.com

Latest Android Jobs

http://www.kotlinweekly.net/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/kotlin-weekly/Kotlin Weekly
Kotlin Weekly

Your weekly dose of Kotlin

https://proandroiddev.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/pad/ProAndroidDev
ProAndroidDev

Android Tech Blogs, Case Studies and Step-by-Step Coding

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
Zalando

Meet one of Berlin's top employers

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
Academy for App Success

Google Play resources tailored for the global droidcon community

Follow us

Team droidcon

Get in touch with us

Write us an Email

 

 

Quicklinks

> Code of Conduct

> Terms and Conditions

> How to hold a conference

> FAQs

> Imprint

Droidcon is a registered trademark of Mobile Seasons GmbH Copyright © 2020. All rights reserved.

powered by Breakpoint One