我是用它解决回调地狱问题,而rxjava比较难用,难以直观理解
点击按钮 执行后台请求,然后更新ui,然后再后台请求网络,再更新前台,然后弹出对话框,然后确认后再后台请求网络
,如果一个按钮做这么多事情,用协程就能很方便的解决.
binding.fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
// 创建一个CoroutineScope与Activity生命周期绑定
val scope = lifecycleScope
scope.launch(Dispatchers.IO) {
// 第一个任务
val resultOne = withContext(Dispatchers.IO) {
delay(2000L) // 模拟耗时操作
"Task 1 result"
}
withContext(Dispatchers.Main) {
binding.textview.text = "Task 1 finished: "
}
// 第二个任务,基于第一个任务的结果
val resultTwo = withContext(Dispatchers.IO) {
delay(3000L) // 模拟耗时操作
"Task 2 result, based on:"
}
withContext(Dispatchers.Main) {
binding.textview.text = ("\nTask 2 finished:")
}
val resultTw3 = withContext(Dispatchers.IO) {
delay(3000L) // 模拟耗时操作
"Task 2 result, based on:"
}
withContext(Dispatchers.Main) {
binding.textview.text = ("\nTask 3 finished:")
}
}
按顺序执行