当前位置:网站首页>The scope builder coroutinescope, runblocking and supervisorscope of kotlin collaboration processes run synchronously. How can other collaboration processes not be suspended when the collaboration pro

The scope builder coroutinescope, runblocking and supervisorscope of kotlin collaboration processes run synchronously. How can other collaboration processes not be suspended when the collaboration pro

2022-06-13 00:46:00 Ango cannot move

coroutineScope And runBlocking difference

runBlocking It's a regular function , and coroutineScope It's a suspend function

They will all wait for the end of their process body and all sub processes , The main difference is that runBolocking Method blocks the current thread to wait . and coroutineScope Just hang up , The underlying thread is freed for other purposes .

runBlocking  Code example 
        binding.btClick7.setOnClickListener {
            runBlocking {

                val job1 = async {
                    delay(1000)
                    Log.e(TAG, "job1 finished")
                    throw IllegalArgumentException()

                }


                val job2 = async {
                    delay(2000)
                    Log.e(TAG, "job2 finished")
                }

            }
            Log.e(TAG, "thread:A")
        }

 app Will flash back

Then change to coroutineScope 

          runBlocking {
                coroutineScope {
                    val job1 = async {
                        delay(1000)
                        Log.e(TAG, "job1 finished")
                        throw IllegalArgumentException()

                    }


                    val job2 = async {
                        delay(2000)
                        Log.e(TAG, "job2 finished")
                    }
                }


            }
            Log.e(TAG, "thread:A")
        }

 

 app It won't go back . The following will not be executed .

If you want to report an error, the rest will not be affected , Use supervisorScope , How to operate

    binding.btClick7.setOnClickListener {
            runBlocking {
                supervisorScope {
                    val job1 = async {
                        delay(1000)
                        Log.e(TAG, "job1 finished")
                        throw IllegalArgumentException()

                    }


                    val job2 = async {
                        delay(2000)
                        Log.e(TAG, "job2 finished")
                    }
                }


            }
            Log.e(TAG, "thread:A")
        }

 coroutineScope A collaboration failed . All other collaborations will be cancelled

supervisorScope  A collaboration failed . It won't affect other brotherhood .

原网站

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