This worked for me:
@Provides
@Singleton
fun dataStore(@ApplicationContext appContext: Context): DataStore<Preferences> =
appContext.createDataStore("settings")
The idea is putting @Singleton
behind the provider method.
Update on Feb 9, 2021:
Preferably, create a manager and provide that:
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
}
}
AppModule:
@InstallIn(SingletonComponent::class)
@Module
class AppModule {
@Provides
@Singleton
fun dataStoreManager(@ApplicationContext appContext: Context): DataStoreManager =
DataStoreManager(appContext)
Update on March 20, 2021:
Version 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
}
}
Update on May 1, 2021:
移除dataStoreManager
个提供者.然后
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
}
}