首先添加依赖:
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
我使用的是MainScope,能在Activity销毁时取消协程块:
class MainActivity : AppCompatActivity() {
val scope = MainScope()
lateinit var tv : TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btn = findViewById<Button>(R.id.button)
tv = findViewById(R.id.textView)
btn.setOnClickListener {
//协程块
scope.launch {
val result = test() //调用suspend函数,异步等待结果
tv.text = result //更新UI
}
}
}
//挂起函数
suspend fun test() : String{
withContext(Dispatchers.IO){
delay(3000) //模拟耗时操作(比如网络请求)
}
return "我是挂起函数的返回值"
}
//销毁时删除协程块,以免内存泄漏
override fun onDestroy() {
super.onDestroy()
scope.cancel()
}
}
这样点击了按钮后就会异步等待3s后给TextView更新UI