Skip to content

Instantly share code, notes, and snippets.

@radityagumay
Last active March 30, 2021 00:05
Show Gist options
  • Save radityagumay/0d2b9e47ff73ca759dc8ed19ff65b536 to your computer and use it in GitHub Desktop.
Save radityagumay/0d2b9e47ff73ca759dc8ed19ff65b536 to your computer and use it in GitHub Desktop.
Singleton Class to Manage DataStore
internal object DataStoreFactory {
private val mapToDataStore = ConcurrentHashMap<String, DataStore<Preferences>>()
fun create(
name: String,
context: Context
): DataStore<Preferences> {
if (mapToDataStore.containsKey(name).not()) {
mapToDataStore[name] = context.getDataStore(
name = name,
corruptionHandler = null,
migrations = listOf(MyCustomSharedPreferenceMigration(
context = context,
sharedPreferencesName = name
))
)
}
return mapToDataStore[name]!!
}
fun create(
name: String,
context: Context,
corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null,
migrations: List<DataMigration<Preferences>>,
scope: CoroutineScope
): DataStore<Preferences> {
if (mapToDataStore.containsKey(name).not()) {
mapToDataStore[name] = PreferenceDataStoreFactory.create(
corruptionHandler = corruptionHandler,
migrations = migrations,
scope = scope
) {
File(context.filesDir, "datastore/$name.preferences_pb")
}
}
return mapToDataStore[name]!!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment