Skip to content

Commit

Permalink
Add ability to initialize models as read-only
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickgold committed Feb 14, 2024
1 parent e59afbc commit d295562
Showing 1 changed file with 6 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -155,14 +155,14 @@ abstract class PreferenceModel(val name: String) {
return prefData
}

suspend fun initialize(context: Context) = registryGuard.withLock {
suspend fun initialize(context: Context, readOnly: Boolean = false) = registryGuard.withLock {
runSafely { datastorePersistenceHandler?.cancelJobsAndJoin() }
persistReq.set(false)
runSafely { datastorePersistenceHandler = PersistenceHandler(context) }
runSafely { datastorePersistenceHandler = PersistenceHandler(context, readOnly) }
}

fun initializeBlocking(context: Context) = runBlocking {
initialize(context)
fun initializeBlocking(context: Context, readOnly: Boolean = false) = runBlocking {
initialize(context, readOnly)
}

/**
Expand Down Expand Up @@ -218,7 +218,7 @@ abstract class PreferenceModel(val name: String) {
}
}

inner class PersistenceHandler(context: Context) {
inner class PersistenceHandler(context: Context, readOnly: Boolean) {
private val datastoreDir: File = context.jetprefDatastoreDir
private val datastoreFile = datastoreDir.jetprefDatastoreFile(name)
private val tempDir: File = context.jetprefTempDir
Expand All @@ -227,7 +227,7 @@ abstract class PreferenceModel(val name: String) {
private val ioJob = ioScope.launch(Dispatchers.IO) {
runSafely { loadPrefs(datastoreFile, reset = true) }
while (isActive) {
if (datastoreReadyStatus.get() && persistReq.getAndSet(false)) {
if (datastoreReadyStatus.get() && persistReq.getAndSet(false) && !readOnly) {
runSafely { persistPrefs() }
}
delay(JetPref.saveIntervalMs)
Expand Down

0 comments on commit d295562

Please sign in to comment.