0
点赞
收藏
分享

微信扫一扫

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)
}

打印日志

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

 上述操作比较复杂

可以使用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()
}

举报

相关推荐

0 条评论