From f3f212bab862d76ff2133a136b4a11abb20c3f9a Mon Sep 17 00:00:00 2001 From: vibhutomer Date: Thu, 14 May 2026 15:43:31 +0530 Subject: [PATCH] Fix: Implement Mutex lock in up-sync to prevent race conditions and duplicate data --- .../sakhi/repositories/SaasBahuSammelanRepo.kt | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/org/piramalswasthya/sakhi/repositories/SaasBahuSammelanRepo.kt b/app/src/main/java/org/piramalswasthya/sakhi/repositories/SaasBahuSammelanRepo.kt index dc49fac8b..73e056cf9 100644 --- a/app/src/main/java/org/piramalswasthya/sakhi/repositories/SaasBahuSammelanRepo.kt +++ b/app/src/main/java/org/piramalswasthya/sakhi/repositories/SaasBahuSammelanRepo.kt @@ -32,6 +32,8 @@ import java.io.File import java.net.SocketTimeoutException import javax.inject.Inject import kotlin.collections.forEach +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock class SaasBahuSammelanRepo @Inject constructor( private val userRepo: UserRepo, @@ -43,6 +45,8 @@ class SaasBahuSammelanRepo @Inject constructor( ) { + + private val syncMutex = Mutex() suspend fun saveSammelanForm(saasBahuSammelanCache: SaasBahuSammelanCache) { withContext(Dispatchers.IO) { @@ -52,13 +56,14 @@ class SaasBahuSammelanRepo @Inject constructor( suspend fun pushUnSyncedRecordsSaasBahuSammelan(): Boolean { - return withContext(Dispatchers.IO) { + return syncMutex.withLock { withContext(Dispatchers.IO) { val user = preferenceDao.getLoggedInUser() ?: throw IllegalStateException("No user logged in!!") val saasBahuList: List = saasBahuDao.getBySyncState(SyncState.UNSYNCED) + if (saasBahuList.isEmpty()) return@withContext true try { saasBahuList.forEach { row -> val imagesParts = (row.sammelanImages ?: emptyList()).mapNotNull { uriStr -> @@ -134,7 +139,7 @@ class SaasBahuSammelanRepo @Inject constructor( return@withContext false } true - } + }} }