From bbab069bcd7a199b61361736006748f14a2b20ff Mon Sep 17 00:00:00 2001 From: Evgeny Poberezkin <2769109+epoberezkin@users.noreply.github.com> Date: Fri, 25 Feb 2022 11:37:47 +0000 Subject: [PATCH] android: replace while true loop with async recursion (#371) --- .../java/chat/simplex/app/model/SimpleXAPI.kt | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/apps/android/app/src/main/java/chat/simplex/app/model/SimpleXAPI.kt b/apps/android/app/src/main/java/chat/simplex/app/model/SimpleXAPI.kt index 2548f20e47..a3380eb861 100644 --- a/apps/android/app/src/main/java/chat/simplex/app/model/SimpleXAPI.kt +++ b/apps/android/app/src/main/java/chat/simplex/app/model/SimpleXAPI.kt @@ -3,6 +3,7 @@ package chat.simplex.app.model import android.util.Log import androidx.compose.runtime.mutableStateOf import chat.simplex.app.* +import chat.simplex.app.views.helpers.withApi import kotlinx.coroutines.* import kotlinx.datetime.Clock import kotlinx.datetime.Instant @@ -36,14 +37,7 @@ open class ChatController(val ctrl: ChatCtrl, val alertManager: SimplexApp.Alert fun startReceiver() { thread(name="receiver") { -// val chatlog = FifoQueue(500) - while(true) { - val json = chatRecvMsg(ctrl) - val r = APIResponse.decodeStr(json).resp - Log.d("SIMPLEX", "chatRecvMsg: ${r.responseType}") - if (r is CR.Response || r is CR.Invalid) Log.d("SIMPLEX", "chatRecvMsg json: $json") - processReceivedMsg(r) - } + withApi { recvMspLoop() } } } @@ -63,6 +57,21 @@ open class ChatController(val ctrl: ChatCtrl, val alertManager: SimplexApp.Alert } } + suspend fun recvMsg(): CR { + return withContext(Dispatchers.IO) { + val json = chatRecvMsg(ctrl) + val r = APIResponse.decodeStr(json).resp + Log.d("SIMPLEX", "chatRecvMsg: ${r.responseType}") + if (r is CR.Response || r is CR.Invalid) Log.d("SIMPLEX", "chatRecvMsg json: $json") + r + } + } + + suspend fun recvMspLoop() { + processReceivedMsg(recvMsg()) + recvMspLoop() + } + suspend fun apiGetActiveUser(): User? { val r = sendCmd(CC.ShowActiveUser()) if (r is CR.ActiveUser) return r.user