当前位置:网站首页>Kotlin starts the process, the difference between launch and async, and starts the process in sequence

Kotlin starts the process, the difference between launch and async, and starts the process in sequence

2022-06-12 03:40:00 Ango cannot move

 launch And async The difference between

       binding.btClick5.setOnClickListener {
            // The main thread executes the coroutine 
            runBlocking {
                //launch  The execution result will not be returned 
                val job1 = launch {
                    delay(200)
                    Log.e(TAG, "onCreate: jbo1 finished.")
                }
                // async  The execution result will be returned 
                val job2 = async {
                    delay(200)
                    Log.e(TAG, "onCreate: job2 finished.")
                    "job2 result"
                }
                Log.e(TAG, "onCreate${ job2.await() }")
            }
        }

Start the process in sequence

Now there are three processes . Want to start first 1

Then start up 2 and 3

How to operate ,

luanch Start up Use join function

       binding.btClick5.setOnClickListener {
            // The main thread executes the coroutine 
            runBlocking {
                //launch  The execution result will not be returned 
                val job1 = launch {
                    delay(2000)
                    Log.e(TAG, "One")
                }
                job1.join()

                val job2 = launch {
                    delay(200)
                    Log.e(TAG, "Two")
                }
                val job3 = launch {
                    delay(200)
                    Log.e(TAG, "Three")
                }
            }
        }

async Words Use await

      binding.btClick5.setOnClickListener {
            // The main thread executes the coroutine 
            runBlocking {
                //launch  The execution result will not be returned 
                val job1 = async {
                    delay(2000)
                    Log.e(TAG, "One")
                }
                job1.await()

                val job2 = async {
                    delay(200)
                    Log.e(TAG, "Two")
                }
                val job3 = async {
                    delay(200)
                    Log.e(TAG, "Three")
                }
            }
        }

 join and await Are all suspended functions , Will not block the main thread

原网站

版权声明
本文为[Ango cannot move]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120335520850.html