Skip to content

Commit

Permalink
feat: update lock logic on local storage repo
Browse files Browse the repository at this point in the history
Now, instead of multiple locks in case of removing or
inserting data, we do the same with a single lock. See: #92 (comment)
  • Loading branch information
wzieba committed Nov 24, 2023
1 parent 95f7a65 commit c32302f
Showing 1 changed file with 19 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ internal interface QueueRepository {
suspend fun insertEvents(toInsert: List<Map<String, Any?>?>)
}

internal class LocalStorageRepository(private val context: Context): QueueRepository {
internal class LocalStorageRepository(private val context: Context) : QueueRepository {

private val mutex = Mutex()

Expand All @@ -38,21 +38,7 @@ internal class LocalStorageRepository(private val context: Context): QueueReposi
}
}

override suspend fun remove(toRemove: List<Map<String, Any?>?>) {
val storedEvents = getStoredQueue()

mutex.withLock {
persistObject(storedEvents - toRemove.toSet())
}
}

/**
* Get the stored event queue from persistent storage.
*
* @return The stored queue of events.
*/
override suspend fun getStoredQueue(): ArrayList<Map<String, Any?>?> = mutex.withLock {

private fun getInternalStoredQueue(): ArrayList<Map<String, Any?>?> {
var storedQueue: ArrayList<Map<String, Any?>?> = ArrayList()
try {
val fis = context.applicationContext.openFileInput(STORAGE_KEY)
Expand All @@ -74,15 +60,26 @@ internal class LocalStorageRepository(private val context: Context): QueueReposi
return storedQueue
}

override suspend fun remove(toRemove: List<Map<String, Any?>?>) = mutex.withLock {
val storedEvents = getInternalStoredQueue()
persistObject(storedEvents - toRemove.toSet())
}

/**
* Save the event queue to persistent storage.
* Get the stored event queue from persistent storage.
*
* @return The stored queue of events.
*/
override suspend fun insertEvents(toInsert: List<Map<String, Any?>?>){
val storedEvents = getStoredQueue()
override suspend fun getStoredQueue(): ArrayList<Map<String, Any?>?> = mutex.withLock {
getInternalStoredQueue()
}

mutex.withLock {
persistObject(ArrayList((toInsert + storedEvents).distinct()))
}
/**
* Save the event queue to persistent storage.
*/
override suspend fun insertEvents(toInsert: List<Map<String, Any?>?>) = mutex.withLock {
val storedEvents = getInternalStoredQueue()
persistObject(ArrayList((toInsert + storedEvents).distinct()))
}

companion object {
Expand Down

0 comments on commit c32302f

Please sign in to comment.