Kotlin 协程的使用/使用MainScope管理协程

   binding.btClick4.setOnClickListener {
            //携程体
            //创建携程
            val continuation = suspend { 5 }
                .createCoroutine(object : Continuation<Int> {
                    override val context: CoroutineContext
                        get() = EmptyCoroutineContext

                    //回调
                    override fun resumeWith(result: Result<Int>) {
                        Log.e(TAG, "resumeWith: ${result} ", )
                    }
                })
            //启动携程
            continuation.resume(Unit)
        }

打印日志

 上述操作比较复杂

可以使用mainScope进行简化

声明成员变量

  private var mainScope= MainScope()
          mainScope.launch {
                var  repoResponse = RetrofitClient
                    .instance
                    .getApi()
                    //suspend 挂起的方法必须在携程体内进行调用
                    .getFeedBack(1, 1)
                //还是在主线程
                binding.tvText.text = "repoResponse :${repoResponse.data!!.data[0].content}"
            }

记得注销的时候注销掉

   override fun onDestroy() {
        super.onDestroy()
        mainScope.cancel()
    }

还有一种写法、在activity实现 

CoroutineScope 接口 并委托给 
MainScope
class CoroutineActivity : AppCompatActivity(),CoroutineScope by MainScope() {
   
   

上述代码就可以简化

        binding.btClick3.setOnClickListener {

           launch {
                var  repoResponse = RetrofitClient
                    .instance
                    .getApi()
                    //suspend 挂起的方法必须在携程体内进行调用
                    .getFeedBack(1, 1)
                //还是在主线程
                binding.tvText.text = "repoResponse :${repoResponse.data!!.data[0].content}"
            }
        }
    override fun onDestroy() {
        super.onDestroy()
       cancel()
    }

猜你喜欢

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