Home > Back-end >  @Synchronized is not working as expected in KMM
@Synchronized is not working as expected in KMM

Time:08-18

I have a Ktor class where I need to do action on unauthorized exception(when token is expired), for this action I need to have synchronized action, otherwise it is not working correctly, the problem is that @Synchronized is not synchronize the action and is not waiting for action to finish for next one.

       fun ktorFunction(){

        HttpResponseValidator {
        handleResponseException { exception ->
            kermit.e { "In ${exception.message}" }

            val clientException =
                exception as? ClientRequestException ?: return@handleResponseException
            val exceptionResponse = clientException.response

            when (exceptionResponse.status) {
                HttpStatusCode.Unauthorized -> {
                    test(){
                        kermit.v { "Error message" }
                    }
            }
         }
      }
   }




@Synchronized
fun test(messageTest: () -> Unit) {
CoroutineScope(Dispatchers.Default).launch {
    delay(3000)
    messageTest()

    }
}

The idea is I want test function to not be called from other thread until it is finished, whatever the action is in it.

CodePudding user response:

launch is a function that starts a coroutine asynchronously and immediately returns, so this is behaving as it should. If you want to synchronize coroutines, you should use Mutex.

I'll leave it alone in the example before, but IMO, it's a code smell to create a CoroutineScope if you're not going to manage its lifecycle.

private val testMutex = Mutex()

fun test(messageTest: () -> Unit) {
    CoroutineScope(Dispatchers.Default).launch {
        testMutex.withLock {
            delay(3000)
            messageTest()
        }
    }
}
  • Related