From 03bb7020f4a9568204a9add22b9d0e8c006c0281 Mon Sep 17 00:00:00 2001 From: Sylvain Berfini Date: Tue, 25 Mar 2025 13:41:47 +0100 Subject: [PATCH] Parse friends in a coroutine scope, no need to do it on the Core's thread --- .../org/linphone/contacts/ContactLoader.kt | 33 ++++++++++++------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/org/linphone/contacts/ContactLoader.kt b/app/src/main/java/org/linphone/contacts/ContactLoader.kt index 211403a59..5f7f6b922 100644 --- a/app/src/main/java/org/linphone/contacts/ContactLoader.kt +++ b/app/src/main/java/org/linphone/contacts/ContactLoader.kt @@ -29,8 +29,14 @@ import androidx.annotation.WorkerThread import androidx.loader.app.LoaderManager import androidx.loader.content.CursorLoader import androidx.loader.content.Loader +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch import java.lang.Exception import org.linphone.LinphoneApplication.Companion.coreContext +import org.linphone.core.Core import org.linphone.core.Factory import org.linphone.core.Friend import org.linphone.core.FriendList @@ -63,6 +69,8 @@ class ContactLoader : LoaderManager.LoaderCallbacks { private val friends = HashMap() + private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + @MainThread override fun onCreateLoader(id: Int, args: Bundle?): Loader { Log.i("$TAG Creating and starting cursor loader") @@ -107,26 +115,27 @@ class ContactLoader : LoaderManager.LoaderCallbacks { } Log.i("$TAG Load finished, found ${cursor.count} entries in cursor") - coreContext.postOnCoreThreadWhenAvailableForHeavyTask({ - parseFriends(cursor) - }, "parse friends") + coreContext.postOnCoreThread { + val core = coreContext.core + val state = core.globalState + if (state == GlobalState.Shutdown || state == GlobalState.Off) { + Log.w("$TAG Core is being stopped or already destroyed, abort") + } else { + scope.launch { + parseFriends(core, cursor) + } + } + } } @MainThread override fun onLoaderReset(loader: Loader) { Log.i("$TAG Loader reset") + scope.cancel() } @WorkerThread - private fun parseFriends(cursor: Cursor) { - val core = coreContext.core - - val state = core.globalState - if (state == GlobalState.Shutdown || state == GlobalState.Off) { - Log.w("$TAG Core is being stopped or already destroyed, abort") - return - } - + private fun parseFriends(core: Core, cursor: Cursor) { try { val contactIdColumn = cursor.getColumnIndexOrThrow(ContactsContract.Data.CONTACT_ID) val mimetypeColumn = cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE)