What is the Kotlin collaboration process?

Posted by spramod on Thu, 10 Feb 2022 02:31:59 +0100

Hi, new classmate. I'm glad you've finally pursued this problem. Maybe you're feeling confused. Various gods have different understanding of the collaborative process. Some say it's a threaded framework, while others say it's lighter than threads. I hope my blog can help you understand the collaborative process from another perspective.

Please believe that any explanation may have changed when it comes to the second population. The official website is the most necessary threshold for us to access any technology. So please open it Kotlin Chinese website . Many people say that the kotlin official website tutorial is not detailed. In fact, it is not. The kotlin Chinese website tutorial is very detailed.

Back to the point:

What is collaborative process?

  • Asynchronous programming
  • experience
  • Language level
  • idea

Pay attention to the above key points and some practical use. It's not difficult to understand

Kotlin collaboration is an asynchronous programming framework based on kotlin syntax. It doesn't bring much performance experience. It can be realized by using thread pool. However, from the perspective of use, the collaboration strives to create an idea of "synchronous and asynchronous programming". As developers, we can be more lazy and switch threads, withContext is enough. The collaborative process brings development comfort, but this comfort is based on kotlin's syntax and nothing else. Therefore, I hope that when you start the process, you can understand it from the perspective of language.

So, what is the collaborative process?

Coprocessing is an asynchronous framework based on Kotlin syntax. It enables developers to write asynchronous code in a synchronous manner without paying attention to redundant operations. It's that simple

How to use the process?

Start a collaborative process

suspend fun main() {
    GlobalScope.launch {
        println("start-up--${System.currentTimeMillis()}---${Thread.currentThread().name}")
        delay(100)
        println("Suspend 100 ms--${System.currentTimeMillis()}---${Thread.currentThread().name}")
    }
    delay(1000)
}
start-up--1579085375166---DefaultDispatcher-worker-1
 Suspend 100 ms--1579085375275---DefaultDispatcher-worker-1

Concurrent use

fun main() {
    runBlocking(Dispatchers.IO) {
        println("start-up--${System.currentTimeMillis()}")
        val as1 = async {
            delay(100)
            println("Concurrency 1--${System.currentTimeMillis()}---${Thread.currentThread().name}")
            "1"
        }
        val as2 = async {
            delay(100)
            println("Concurrency 2--${System.currentTimeMillis()}---${Thread.currentThread().name}")
            "2"
        }
        println("as1=${as1.await()},as2=${as2.await()}")
    }
}
start-up--1579085205199
 Concurrency 1--1579085205313---DefaultDispatcher-worker-3
 Concurrency 2--1579085205313---DefaultDispatcher-worker-2
as1=1,as2=2

It's not very comfortable to observe the running results of the above demo. It seems that the synchronous mode is internally asynchronous operation. What's the meaning of hanging in the notes above?

What is suspend?

Looking at the above print log, it is not difficult to find that when calling the delay function, the thread does not stop. Relatively speaking, it is only that our collaboration code block is suspended and waiting for recovery. Only after the execution of the previous pending function is completed can our coroutine code block continue to execute. Borrow a picture to illustrate as follows:

So the so-called Hang is actually a process at the code level, so that we can write asynchronous code in synchronous form.

Non blocking program?

The so-called non blocking is actually to switch threads and observe the changes of print logs. We can find that when we directly globalscope When launch starts a collaboration, the thread running at this time is the default thread, so the collaboration is called a non blocking implementation.

Function of suspend keyword

First look at the picture below

When the function decorated with suspend is called suspended function, what is the function of suspended function? Why is the suspend flag of test black?

Keep looking at the screenshot

Why can suspended functions only be used in suspended functions??

Let's move on: look at java bytecode

What is this Continuation? Literally, it means Continuation. How do we understand that?

Generally speaking, Continuation represents < the concept of remaining calculation >, that is, the code to be executed next. The official explanation is called the starting point

For example, I have a piece of code:

println("123".length)

The first one is "123" Length, and then execute println to print the length. At this time, execute "123" Length can be used as a hanging point, that is, the code stops here and waits for the calculation result. However, at this time, the internal thread does not stop. When the calculation is finished, that is, the hanging ends, and then execute our print statement.

Switch to our suspend, which represents the function of a flag. The function represented by suspend is called the suspend function. When the compiler encounters the function with this flag, it will know that it is a potentially time-consuming operation.

Why can suspended functions only be used in suspended functions?

Because ordinary function parameters do not have Continuation, it is equivalent to no hanging point, and the compiler cannot judge, so an error will be reported at this time.

Why is the suspend flag of test black?

The compiler knows that it is a suspended function, but there is no suspended function inside test, so the compiler prompts at this time. So this function doesn't work at all? The function is to limit this function to suspend function calls.

Use in Android

Countdown function

class Main3Activity : AppCompatActivity() {
    private val mainScope = CoroutineScope(Dispatchers.Default)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main3)
        progressBar.max = 100
        mainScope.launch {
            (1..100).forEach {
                delay(100)
                withContext(Dispatchers.Main) {
                    progressBar.secondaryProgress = it
                }
            }
        }

    }
  
  onDestory(){
    //Remember to close
  }
  
}

Use with ViewModel

class MainViewModel : ViewModel() {
    fun test() {
        viewModelScope.launch {

        }
    }
}

When the ViewModel is cancelled, the collaboration will be closed automatically

Use with Lifecycle

Import the following dependencies implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-rc03"

So the countdown code just now is changed as follows:

class Main3Activity : AppCompatActivity() {
  			....
        lifecycleScope.launch {
           ...
        }
    }
}

Similarly, when the fragment or Activity is closed, the collaboration will also be closed automatically.

Looking at the source code, you will find that the implementation methods of viewModelScope and lifecycle lifecycle scope in viewModel are the same:

In this article, we don't search too much from the source code. What is the collaborative process? Try to start from the perspective of grammar and users, and take everyone to understand the collaborative process from the side. I hope everyone can have their own understanding.