Koltin coroutine, introduction to Coroutines

What is a coroutine?

Official description: Coroutines simplify asynchronous programming by putting complexity into libraries. The logic of the program can be expressed sequentially in the coroutine, and the underlying library will solve its asynchrony for us. The library can package the relevant parts of the user code as callbacks, subscribe to related events, and schedule execution on different threads (or even different machines), while the code remains as simple as sequential execution.
Coroutines are like very lightweight threads. Threads are scheduled by the system, and the overhead of thread switching or thread blocking is relatively large. The coroutine depends on the thread, but the thread does not need to be blocked when the coroutine hangs, which is almost costless. The coroutine is controlled by the developer. So coroutines are also like user-mode threads, very lightweight, and any number of coroutines can be created in a thread.
The important thing about a coroutine is that when it hangs, it does not block other threads. The underlying library of the coroutine also handles blocking tasks asynchronously, but these complex operations are encapsulated by the underlying library. The program flow of the coroutine code is sequential, and there is no need for a bunch of callback functions. Just like the synchronous code, it is also easy to understand. Debugging and development. It is controllable, the execution and end of the thread are scheduled by the operating system, and the coroutine can manually control its execution and end.

use

Add dependency

implementation “org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.1”

Launch

This is the most common way to start a coroutine. It eventually returns a Job type object. This Job type object is actually an interface, which contains many commonly used methods. Let's take a look at the simple use:

     LaunchJob.setOnClickListener {
    
    
            log(START)
            GlobalScope.launch {
    
    
                delay(3000)
                log(RUN)
            }
            log(END)
        }

As a result, it can be seen from the results that launch will not block the main thread

D/MainActivity: START---> Time: 11:33:54.289, 线程:main
D/MainActivity: END---> Time: 11:33:54.324, 线程:main
D/MainActivity: RUNING---> Time: 11:33:57.334, 线程:DefaultDispatcher-worker-1

Coroutine body-synchronization

   Suspend.setOnClickListener {
    
    
            log(START)
            GlobalScope.launch {
    
    
                val sum1 = job1()
                val sum2  =job2()
                val sum = sum1+sum2
                Log.d(
                    "MainActivity",
                    "Runing---> Time: ${
      
      getNow()}, 线程:${
      
      Thread.currentThread().name},Result: $sum"
                )
            }
            log(END)
        }
    private suspend fun job1():Int{
    
    
        delay(2000)
        return 1+1
    }
    private suspend fun job2():Int{
    
    
        delay(3000)
        return 2+2
    }

As a result, it can be seen from the results that the two methods are executed sequentially, which takes 5 seconds in total

D/MainActivity: START---> Time: 11:37:39.675, 线程:main
D/MainActivity: END---> Time: 11:37:39.676, 线程:main
D/MainActivity: Runing---> Time: 11:37:44.691, 线程:DefaultDispatcher-worker-5,Result: 6

Coroutine Body-Asynchronous

    Async.setOnClickListener {
    
    
            log(START)
            GlobalScope.launch {
    
    
                val sum1 = GlobalScope.async {
    
     job1() }
                val sum2 = GlobalScope.async {
    
     job2() }
                val sum = sum1.await()+sum2.await()
                Log.d(
                    "MainActivity",
                    "Runing---> Time: ${
      
      getNow()}, 线程:${
      
      Thread.currentThread().name},Result: $sum"
                )
            }
            log(END)
        }

As a result, it can be seen from the results that the two methods are executed asynchronously, which takes a total of 3s

D/MainActivity: START---> Time: 11:39:45.351, 线程:main
D/MainActivity: END---> Time: 11:39:45.360, 线程:main
D/MainActivity: Runing---> Time: 11:39:48.354, 线程:DefaultDispatcher-worker-6,Result: 6

Kotlin coroutine

entry learning Kotlin coroutine

Guess you like

Origin blog.csdn.net/qq_33431394/article/details/107379774