Home > Software engineering >  Does coroutines maintain order in if conditions?
Does coroutines maintain order in if conditions?

Time:08-24

I was thinking of doing something like this when coding an if statement, my goal is to first check the coroutine that will set the boolean flag to true or false for return, and then check that also the boolean flag that is inside the same if condition and function will yield to the expected value.

My question is if the evaluation inside the if statement of the boolean value will be before or after the coroutine ends.

In other words, I have this function

if(myBlockingCoroutineFunction() && !myCondition) return@launch


private suspend myBlockingCoroutineFunction(): Boolean {
   //some logic here
   //Updates the local myCondition
   myCondition = false
   return true
 }

and my question is if blocking the first parameter in the if statement this will be the same as

if(myBlockingCoroutineFunction())  {
  if(!myCondition)
  return@launch
}

Internally as I know the if statement will compare the two addresses of the parameters in order to see if they match the predicate to continue, but at this case I don't really know certainly if the myCondition value will be stored as the coroutine executes and then it will be compared with the results of the function but without taking in note that myCondition has changed

CodePudding user response:

First of all, it's bit non-sensical for a suspend function to have blocking in it's name, since by convention, suspend functions must never block. See the Suspending Convention section in this article by the design lead of Kotlin coroutines.

But, regardless of whether the function is a suspend function or if it blocks or not, code will execute synchronously, just as if this were not in a coroutine. In your example, myBlockingCoroutineFunction() in the if condition will be executed, and after it returns, the next part of the Boolean expression will be evaluated.

Within the same coroutine, your myCondition variable or property has an order guarantee and no synchronization is needed. If it's modified from multiple different coroutines simultaneously, depending on your use case, you might need to use mutual exclusion to protect the order of events.

  • Related