Hi, I have a function that I want to suspend until...
# coroutines
l
Hi, I have a function that I want to suspend until I resume it manually from another function:
Copy code
private suspend fun sendPacketWithAcknowledgement(packet: RequestPacket) {
        try {
            withTimeout(PACKET_CONFIRMATION_TIMEOUT) {
                sendPacket(packet.bytes)
            }
            // Wait here until ack packet received
            // mutex.lock() // I thought this will suspend the code here and on mutex.unlock() it will resume here
        } catch (e: TimeoutCancellationException) {
            // do sth.
        }
    }
On caller site:
Copy code
sendPacketWithAcknowledgement(StartCommunication()) // should be sequential
isCommunicationEstablished = true
The caller code should behave sequential, so that
isCommunicationEstablished = true
is only processed, when the ack packet is received and the suspension is resumed manually. I thought mutex would fit here but I guess I didn't use it the right away. It's a bluetooth classic scenario btw. So does someone know how I can achieve this behavior?
o
Yes, use the
suspendCoroutine
function to convert callback-based code to suspending code. https://elizarov.medium.com/callbacks-and-kotlin-flows-2b53aa2525cf
l
Thanks I got it managed ­čÖé