Desire Layer utilizing Knowledge Retailer- Android Jetpack | by Saurabh Pant | Nov, 2022 | Mage Tech

virtually Desire Layer utilizing Knowledge Retailer- Android Jetpack | by Saurabh Pant | Nov, 2022 will lid the newest and most present opinion one thing just like the world. admission slowly suitably you comprehend with out issue and accurately. will layer your data proficiently and reliably

Android preferences tutorial

Supply: 123rf

In Android apps, we usually retailer easy information units utilizing native preferences. These preferences are easy, quick, and simple to entry. Or we do it with SharedPreferences or DataStore Preferences. In a use case the place we’re utilizing SharedPreferences and need to migrate to DataStore Preferences then it may have an effect on many elements of our code.

So on this article we’re going to:

  • Create a separate module for our preferences and we’ll preserve the remainder of the modules no matter the kind of preferences we’re utilizing.
  • Use Hilt for dependency injection from our choice module to our major app module

We’ll take into account that:

  • Our app merely accepts a username
  • Because the person sorts the title, it’s instantly saved and up to date and displayed over a textual content view on the identical display.

We’ll create a brand new module as an android library module and title it as native choice. To create a brand new module, proper click on in your mission title -> New -> Module

Then choose Android Library and fill within the particulars as anticipated.

Click on end and we’ll create our native choice module.

Though this appears quite simple, we will have several types of preferences, for instance, UserDevicePreference, LoginPreference, AppPreference, and many others.

On this structure, we now have uncovered solely the endpoints required for our major :app module associated to a person’s preferences by means of the UserPreference interface. Now him :app don’t fret about how and the place the info is saved.

Setting DataStore preferences

So as to add information storage preferences, we have to add the dependency in local-preference construct.gradle

// inside local-preference construct.gradle
implementation "androidx.datastore:datastore-preferences:1.0.0"

We outline our UserPreference interface as follows

interface UserPreference 

* returns person title circulate
* */
enjoyable userName(): Movement<String>

* saves person title in information retailer
* */
droop enjoyable saveUserName(title: String)

The capabilities are self-explanatory. We offer your UserDataStore implementation as:

class UserDataStore @Inject constructor(
personal val dataStore: DataStore<Preferences>
): UserPreference

override enjoyable userName(): Movement<String>
return dataStore.information

.map choice ->
choice[KEY_USER_NAME] ?: ""

override droop enjoyable saveUserName(title: String)
dataStore.edit choice ->
choice[KEY_USER_NAME] = title

Getting information from the datastore returns a stream that could be a nice deal. Right here we merely return our saved username as a stream. That is useful as a result of any change to the username will replace our circulate immediately and we will work on the newest modifications.

Saving the username can be fairly simple, however word that it is a sleep perform and have to be known as inside a routine scope.

Grip Configuration

We inject the datastore object into the UserDataStore utilizing Hilt. So as to add Hilt we have to add a plugin and dependency in native choice construct.gradle as under (similar for :app module)

id 'kotlin-kapt'

// hilt
implementation ""
kapt ""

And since it is a completely different module than :app and each modules will use Hilt, so we outline the Hilt plugin generally inside the construct.gradle file on the mission stage as follows:

id '' model '2.44' apply false

Going again to our native choice module, we offer our information storage object as a single as follows:

object DataStoreModule

enjoyable provideDataStore(@ApplicationContext context: Context) : DataStore<Preferences>
return PreferenceDataStoreFactory.create(
corruptionHandler = ReplaceFileCorruptionHandler(
produceNewData = emptyPreferences()
produceFile = context.preferencesDataStoreFile("user_data")

And we offer the implementation of the UserPreference object as follows:

summary class UserPreferenceModule

summary enjoyable bindUserPreferences(impl: UserDataStore): UserPreference

To notice that we offer UserPreference inside ViewModelComponent, it is because this choice object will probably be legitimate till our view mannequin lives.

Since we now have our preferences set, we will now use them in our major software. First we add the native choice module to our :app module including the dependency as follows:

// Native preferences
implementation mission(path: ':local-preference')

Then we add hilt on our major :app module in the identical method we did for the native choice. We mark our major software as HiltApplication.

class DataStoreApplication: Utility()

We then create our MainViewModel view mannequin and inject a UserPreference into it. We additionally mark it as HiltViewModel and it seems like this:

class MainViewModel @Inject constructor(
personal val userPreference: UserPreference
) : ViewModel()

We then outline our strategies within the view fashions to learn and write the username as proven:

* username circulate to look at modifications in person title
* */
val userName: StateFlow<String> = userPreference.userName().filter

"No saved information"

* save person title
* */
enjoyable saveUserName(title: String)

userName is a stream that’s transformed to a dynamic stream utilizing stateIn and is collected within the UI with the lifecycle state as proven under.

val userName: String by viewModel.userName.collectAsStateWithLifecycle()

We may have used the conventional circulate, however then we must make a distinct association to take a look at it with the UI lifecycle.

The username is solely saved in a coroutine scope utilizing the UserPreference object.

Be aware: To make use of the collectAsStateWithLifecycle() perform, we have to add a dependency as follows:

implementation "androidx.exercise:activity-ktx:1.6.1"

Then lastly we use all of the settings in our composable UI and show the info as it’s saved and up to date.

bam! We create a separate layer for our preferences. This additionally helps pace up development time on a large-scale mission. You’ll be able to attempt to do extra with it and mess around with completely different eventualities.

Yow will discover the total code on GitHub.

Join with me (if the content material is beneficial to you) at

Till subsequent time…

Well being!

I want the article virtually Desire Layer utilizing Knowledge Retailer- Android Jetpack | by Saurabh Pant | Nov, 2022 provides notion to you and is beneficial for appendage to your data

Preference Layer using Data Store- Android Jetpack | by Saurabh Pant | Nov, 2022