Views: 10 visits

What are Coroutines?

A series of Android programming tutorials to teach Coroutines in Android. Coroutines were added to Android with Kathleen. Join us to learn more about this code.

Coroutines = Co + Routines

Here co means cooperation and routines means function. This means that the functions work in relation to each other.

Well, let’s go to the example. Below is a simple example with two functions

 

functionA

fun functionA(case: Int) {
    when (case) {
        1 -> {
            taskA1()
            functionB(1)
        }
        2 -> {
            taskA2()
            functionB(2)
        }
        3 -> {
            taskA3()
            functionB(3)
        }
        4 -> {
            taskA4()
            functionB(4)
        }
    }
}

functionB

fun functionB(case: Int) {
    when (case) {
        1 -> {
            taskB1()
            functionA(2)
        }
        2 -> {
            taskB2()
            functionA(3)
        }
        3 -> {
            taskB3()
            functionA(4)
        }
        4 -> {
            taskB4()
        }
    }
}

Here, when functionA takes a value of one in the input, functionB will run, and when functionB completes, function will run in FunctionA. This is called cooperation. Using Coroutines, you can easily work without using case you can implement.

There are two types of Coroutines:

Stackless
Stackful

kotlin uses stackless coroutines, meaning that coroutines do not have their own stack, so fucntions do not work on native crunches as maps. (Simply put, they work in reserved crisp.)

This is described on the Kathleen Coroutines website.

Coroutine is primarily a light crisp. It works like crisp. Coroutines can run in parallel. They can also wait and work with each other. The biggest difference between coroutine and crisp is that they are free and cheap. You can create thousands of coroutines but you will not have any performance problems. See, but if you do the same crispy, you will definitely face the problem of memory leak.

Coroutines are not a substitute for crisp, but they are more like a framework for crisp management.

 

suspend fun fetchAndShowUser() {
     val user = fetchUser() // fetch on IO thread
     showUser(user) // back on UI thread
}

 

ادامه مطلب