使用Kotlin协程在Activity中调用Retrofit API



我想在点击按钮后加载一些数据。我想出了下面的解决方案,它的工作原理如我所料。但是我刚刚开始学习kotlin协程,我想让其他人对我的代码进行注释。例如,我可以使用lifecycleScope.launch更新UI吗?我可以用withContext(Dispatchers.Main)代替,但有区别吗?

我的实现总体上是好的吗?是否存在可以优化/重构的内容?

我明白最好使用ViewModel并在那里进行API调用,但在这种情况下,我希望所有的动作都发生在活动内部。

class MainActivity : AppCompatActivity() {
var apiCallScope: CoroutineScope? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<View>(R.id.btn_load_content).setOnClickListener {
// Cancel previous API call triggered by the click.
// I don't want to have multiple API calls executing at the same time.
apiCallScope?.cancel()
showProgress(true)
apiCallScope = CoroutineScope(Dispatchers.IO)
apiCallScope!!.launch {
// Execute Retrofit API call
val content = api.loadContent().await()
// Update UI with the content from API call on main thread
lifecycleScope.launch {
showProgress(false)
drawContent(content)
}
}
}
}
override fun onDestroy() {
super.onDestroy()
apiCallScope?.cancel()
}
private fun showProgress(show: Boolean) {
// TODO implement
}
private fun drawContent(content: String) {
// TODO implement
}
}

最好使用ViewModel来进行这种类型的操作,而不是在Activity中执行它们,特别是在onCreate方法中。

ViewModel给出了viewModelScope属性,如果清除ViewModel以避免消耗资源,在此范围内启动的任何协程都会自动取消。

最新更新