【发布时间】:2019-03-09 23:58:03
【问题描述】:
我是协程新手。所以我只是想知道使用它们的最佳方式是什么。
我的场景/用例是我想在 IO thread 上进行 API 调用并在 Main thread 上观察结果并更新 UI。另外,当调用片段的onDestoryView() 时,我想取消我的工作。
我的片段要求演示者提供一些更新。所以我的演示者有一个像这样运行的协程 -
class MyPresenter(view: MyView,
private val coroutineCtx: CoroutineContext = Dispatchers.Main) : CoroutineScope {
private val job: Job = Job()
private var view: MyView? = null
init {
this.view= view
}
override val coroutineContext: CoroutineContext
get() = job + coroutineCtx
fun updateData() = launch{
//repo is singleton
val scanResult = repo.updateData()
when(scanResult) {
sucess -> { this.view.showSuccess()}
}
}
fun stopUpdate() {
job.cancel()
}
}
在我的存储库中,
suspend fun updateData(): Result<Void> {
val response = API.update().await()
return response
}
我是否正确使用协程?如果是,我的job.cancel() 似乎永远不会工作,尽管我从片段的onDestroyView() 调用它。
【问题讨论】:
-
我听说最好使用
SupervisorJob而不是Job作为协程范围的根作业。
标签: android kotlin kotlin-coroutines