kotlin 协程withContext切换线程

       GlobalScope.launch(Dispatchers.Main) {
                //切到子线程进行操作
                val repoResponse: Response<FeedBackLists>
                withContext(Dispatchers.IO) {
                    repoResponse = RetrofitClient
                        .instance
                        .getApi()
                        //suspend 挂起的方法必须在携程体内进行调用
                        .getFeedBack(1, 1)
                }
                //还是在主线程
                binding.tvText.text = "repoResponse :${repoResponse.data!!.data[0].content}"
            }

withContext 可以将当前线程从主线程切换到io线程。然后执行完毕再切换回来到ui线程执行操作

这样做的好处就是消除了

代码嵌套

而是写成上下级关系就可以进行协程合作

 withContent也可以嵌套到suspend fun 方法当中

挂起是非阻塞的线程

launch里面的东西就是协程。

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/125251432