From b2e518d37cdf5d15056302ae6713be7bcea0164f Mon Sep 17 00:00:00 2001 From: Gideon Okuro Date: Wed, 11 Dec 2024 19:01:12 +0300 Subject: [PATCH] logSyncInSharedPrefs improvements to prevent ANR --- .../ui/sync/DashboardElementActivity.kt | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/org/ole/planet/myplanet/ui/sync/DashboardElementActivity.kt b/app/src/main/java/org/ole/planet/myplanet/ui/sync/DashboardElementActivity.kt index f4e213c23d..d6e2042da8 100644 --- a/app/src/main/java/org/ole/planet/myplanet/ui/sync/DashboardElementActivity.kt +++ b/app/src/main/java/org/ole/planet/myplanet/ui/sync/DashboardElementActivity.kt @@ -20,9 +20,12 @@ import androidx.fragment.app.FragmentManager import androidx.lifecycle.lifecycleScope import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.google.android.material.bottomnavigation.BottomNavigationView +import io.realm.Realm import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import org.ole.planet.myplanet.R import org.ole.planet.myplanet.callback.OnRatingChangeListener import org.ole.planet.myplanet.model.RealmUserChallengeActions.Companion.createAction @@ -121,10 +124,24 @@ abstract class DashboardElementActivity : SyncActivity(), FragmentManager.OnBack } fun logSyncInSharedPrefs() { - lifecycleScope.launch { - if (isServerReachable(Utilities.getUrl())) { - startUpload("dashboard") - createAction(mRealm, "${profileDbHandler.userModel?.id}", null, "sync") + lifecycleScope.launch(Dispatchers.IO + SupervisorJob()) { + try { + val isReachable = isServerReachable(Utilities.getUrl()) + if (isReachable) { + withContext(Dispatchers.Main) { + startUpload("dashboard") + } + + withContext(Dispatchers.IO) { + Realm.getDefaultInstance().use { realm -> + realm.executeTransaction { + createAction(realm, "${profileDbHandler.userModel?.id}", null, "sync") + } + } + } + } + } catch (e: Exception) { + e.printStackTrace() } } }