这对我有用:
@Provides
@Singleton
fun dataStore(@ApplicationContext appContext: Context): DataStore<Preferences> =
appContext.createDataStore("settings")
这个想法是把@Singleton
位于提供者方法后面。
2021 年 2 月 9 日更新:
最好创建一个manager https://github.com/Drjacky/MVVMTemplate/blob/master/presentation/src/main/kotlin/app/web/drjackycv/presentation/datastore/DataStoreManager.kt并规定:
class DataStoreManager(appContext: Context) {
private val settingsDataStore = appContext.createDataStore("settings")
suspend fun setThemeMode(mode: Int) {
settingsDataStore.edit { settings ->
settings[Settings.NIGHT_MODE] = mode
}
}
val themeMode: Flow<Int> = settingsDataStore.data.map { preferences ->
preferences[Settings.NIGHT_MODE] ?: AppCompatDelegate.MODE_NIGHT_UNSPECIFIED
}
}
应用程序模块 https://github.com/Drjacky/MVVMTemplate/blob/master/app/src/main/kotlin/app/web/drjackycv/mvvmtemplate/di/module/AppModule.kt:
@InstallIn(SingletonComponent::class)
@Module
class AppModule {
@Provides
@Singleton
fun dataStoreManager(@ApplicationContext appContext: Context): DataStoreManager =
DataStoreManager(appContext)
2021 年 3 月 20 日更新:
版本1.0.0-alpha07
private val Context.dataStore by preferencesDataStore("settings")
class DataStoreManager(appContext: Context) {
private val settingsDataStore = appContext.dataStore
suspend fun setThemeMode(mode: Int) {
settingsDataStore.edit { settings ->
settings[Settings.NIGHT_MODE] = mode
}
}
val themeMode: Flow<Int> = settingsDataStore.data.map { preferences ->
preferences[Settings.NIGHT_MODE] ?: AppCompatDelegate.MODE_NIGHT_UNSPECIFIED
}
}
2021 年 5 月 1 日更新:
@Florian 完全正确,我忘了这一点。
Remove dataStoreManager
来自 DI 模块的提供者。只是:
private val Context.dataStore by preferencesDataStore("settings")
@Singleton //You can ignore this annotation as return `datastore` from `preferencesDataStore` is singletone
class DataStoreManager @Inject constructor(@ApplicationContext appContext: Context) {
private val settingsDataStore = appContext.dataStore
suspend fun setThemeMode(mode: Int) {
settingsDataStore.edit { settings ->
settings[Settings.NIGHT_MODE] = mode
}
}
val themeMode: Flow<Int> = settingsDataStore.data.map { preferences ->
preferences[Settings.NIGHT_MODE] ?: AppCompatDelegate.MODE_NIGHT_UNSPECIFIED
}
}