Coverage Summary for Class: UserPreferencesModule (com.vsevolodganin.clicktrack.di.module)
| Class |
Method, %
|
Branch, %
|
Line, %
|
Instruction, %
|
| UserPreferencesModule |
0%
(0/3)
|
0%
(0/2)
|
0%
(0/10)
|
0%
(0/62)
|
| UserPreferencesModule$ProvideUserPreferencesMetroFactory |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/11)
|
| UserPreferencesModule$ProvideUserPreferencesMetroFactory$Companion |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/11)
|
| UserPreferencesModule$runDataStoreMigration$1 |
0%
(0/1)
|
0%
(0/8)
|
0%
(0/8)
|
0%
(0/224)
|
| Total |
0%
(0/6)
|
0%
(0/10)
|
0%
(0/20)
|
0%
(0/308)
|
package com.vsevolodganin.clicktrack.di.module
import android.app.Application
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.preferencesDataStoreFile
import com.russhwolf.settings.ExperimentalSettingsApi
import com.russhwolf.settings.SharedPreferencesSettings
import com.russhwolf.settings.coroutines.FlowSettings
import com.russhwolf.settings.coroutines.toFlowSettings
import com.vsevolodganin.clicktrack.di.component.ApplicationScope
import dev.zacsweers.metro.BindingContainer
import dev.zacsweers.metro.ContributesTo
import dev.zacsweers.metro.Provides
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
@ContributesTo(ApplicationScope::class)
@BindingContainer
object UserPreferencesModule {
@OptIn(ExperimentalSettingsApi::class)
@Provides
fun provideUserPreferences(application: Application): FlowSettings {
return SharedPreferencesSettings.Factory(application).create("user_preferences")
.toFlowSettings(Dispatchers.IO)
.also { it.runDataStoreMigration(application) }
}
@OptIn(ExperimentalSettingsApi::class)
private fun FlowSettings.runDataStoreMigration(application: Application) {
val legacyDataStoreFile = application.preferencesDataStoreFile("user_preferences")
if (legacyDataStoreFile.exists()) {
val legacyDataStore = PreferenceDataStoreFactory.create(
migrations = listOf(SharedPreferencesMigration(application, "user_preferences")),
produceFile = { application.preferencesDataStoreFile("user_preferences") },
)
runBlocking {
val legacyData = legacyDataStore.data.first()
legacyData.asMap().forEach { (key, value) ->
// We are inspecting only those types that were used at the time of writing.
when (value) {
is Boolean -> putBoolean(key.name, value)
is Int -> putInt(key.name, value)
is Long -> putLong(key.name, value)
is String -> putString(key.name, value)
}
}
}
legacyDataStoreFile.delete()
}
}
}