当前位置:网站首页>Kotlin coroutine withcontext switch thread

Kotlin coroutine withcontext switch thread

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

       GlobalScope.launch(Dispatchers.Main) {
                // Switch to the sub thread for operation 
                val repoResponse: Response<FeedBackLists>
                withContext(Dispatchers.IO) {
                    repoResponse = RetrofitClient
                        .instance
                        .getApi()
                        //suspend  The suspended method must be called in Ctrip 
                        .getFeedBack(1, 1)
                }
                // Or in the main thread 
                binding.tvText.text = "repoResponse :${repoResponse.data!!.data[0].content}"
            }

withContext You can switch the current thread from the main thread to io Threads . Then switch back to after the execution ui Threads perform operations

The advantage of doing so is to eliminate

Code nesting

Instead, it can be written as a parent-child relationship to facilitate process cooperation

 withContent Can also be nested into suspend fun Among the methods

Suspend is a non blocking thread

launch What's inside is Xiecheng .

原网站

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