Last active
March 30, 2021 00:05
-
-
Save radityagumay/0d2b9e47ff73ca759dc8ed19ff65b536 to your computer and use it in GitHub Desktop.
Singleton Class to Manage DataStore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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