A simple question about Kotlin Coroutines or how not to get lost in measurements

Imagine that the red area is inside the main() function and the green area is inside launch – these are two different dimensions.
By the way, code inside launch – this is a “coroutine”. From now on I will call launch like this

Let's find out the difference between the measurements:

  • Red – this is the main dimension (the main flow of the program)

  • Green – measurement, where time delays (delay) and sequence of code execution may vary from the main program flow (red dimension)

When running the main() function at first red dimension starts execution while coroutines can start their work in parallel or after starting red

What ultimately happens in our code:

When we run main(), main thread performs println(“Red Dimension”)without waiting for delay() in the coroutine, and the program ends with the phrase Process finished with exit code 0

But how to print first “Green Dimension” and then “Red Dimension”?

We need to tell the program: “wait until it completes” delay(1000)and only then print “red dimension”

For these purposes we can use the function join()

Let's add it:

join() suspends red dimension until green completes delay()

We see an error:

We are asked to add to the main() function word suspend

suspend means that function can pause its implementation
Please note that the function is suspended main(), and the coroutine is active and running

So now red dimension will be suspended

By adding join()we have:

And now the final question!

Let's imagine that it is not possible to use join()

How can I make it display again:
Green dimension
Red Dimension

Answer to the question. Don't open ahead of time, think for yourself first

We need to move delay() to the red dimension

Now suspend main() cannot bypass delay() and will wait for it to complete

Things to remember:

  1. suspend functions must be called inside coroutine or other suspend functions

  2. join() is the suspend function. In our case, it suspends another suspend function (namely main)

  3. suspend functions are highlighted with a special icon

4. Coroutines are launched not instantlythis takes some time

More small tasks:

What do you think this code will output:
Check the answer in IDEA or write in the comments 🙂

Problem 1

Problem 1

Problem 2

Problem 2

Problem 3

Problem 3

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *