Skip to content

Commit 46ccb80

Browse files
committed
Ensure that only one DataStore active for the same file.
1 parent 033b6fd commit 46ccb80

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

libraries/preferences/impl/src/main/kotlin/io/element/android/libraries/preferences/impl/store/DefaultPreferencesDataStoreFactory.kt

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,27 @@ import androidx.datastore.preferences.preferencesDataStore
1414
import com.squareup.anvil.annotations.ContributesBinding
1515
import io.element.android.libraries.di.AppScope
1616
import io.element.android.libraries.di.ApplicationContext
17+
import io.element.android.libraries.di.SingleIn
1718
import io.element.android.libraries.preferences.api.store.PreferenceDataStoreFactory
19+
import java.util.concurrent.ConcurrentHashMap
1820
import javax.inject.Inject
1921

22+
@SingleIn(AppScope::class)
2023
@ContributesBinding(AppScope::class)
2124
class DefaultPreferencesDataStoreFactory @Inject constructor(
2225
@ApplicationContext private val context: Context,
2326
) : PreferenceDataStoreFactory {
27+
private val dataStoreHolders = ConcurrentHashMap<String, DataStoreHolder>()
28+
2429
private class DataStoreHolder(name: String) {
2530
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = name)
2631
}
32+
2733
override fun create(name: String): DataStore<Preferences> {
28-
return with(DataStoreHolder(name)) {
34+
val holder = dataStoreHolders.getOrPut(name) {
35+
DataStoreHolder(name)
36+
}
37+
return with(holder) {
2938
context.dataStore
3039
}
3140
}

0 commit comments

Comments
 (0)