Using Android JetPack’s PreferenceStorage with Dagger Hilt

Shubham Gupta
2 min readNov 7, 2020

As you might be already aware, Jetpack DataStore’s Preference Storage is the recommended solution to store data instead of SharedPreferences. It is based on Kotlin Coroutines and Flow. If you do not know about it, give it a read here.

Note: This article does not cover the Proto DataStore.

This post is about integrating Preference Storage with Dagger Hilt. So let’s get started.

  1. Include the dependencies in the app level gradle file i.e. app/build.gradle. Check the latest version for Preference Data Store here and Dagger here.
...
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {
// dagger hilt
implementation "com.google.dagger:hilt-android:2.28-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"
// Preferences DataStore
implementation "androidx.datastore:datastore-preferences:1.0.0- alpha02"
}

2. Add the hilt-android-gradle-plugin plugin to your project's root build.gradle file:

buildscript {
...
dependencies {
...
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
}
}

3. Create the Preference Storage class

4. Use Dagger Hilt to provide instances of Preference Storage class

@Module
@InstallIn(ApplicationComponent::class)
abstract class StorageModule {

@Binds
abstract fun providesPreferenceStorage(
appPreferenceStorage: AppPrefsStorage
): PreferenceStorage
}

5. Create an Application class to initialize Dagger Hilt. Don’t forget to add this class to the AndroidManifest.xml file.

@HiltAndroidApp
class MainApplication : Application()

6. Use your newly created Preference Storage class.

@AndroidEntryPoint
class PrefsTestActivity : AppCompatActivity() {

@Inject
lateinit var prefStorage: PreferenceStorage

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

lifecycleScope.launchWhenCreated {

// get value from Flow using the firstOrNull() operator
val isDarkTheme = prefStorage.isDarkTheme.firstOrNull()
isDarkTheme?.let {
Timber.e("isDarkTheme: $it")
}
// set dark theme
prefStorage.setIsDarkTheme(true)
}
}
}

That’s it. If you have any questions or suggestions, feel free to comment.

--

--

Shubham Gupta

Programming Enthusiast, Google Certified Android Developer, Sarcasm and Humour lover, Being a better me.