【发布时间】:2018-05-07 18:56:54
【问题描述】:
所以我正在将一个示例应用程序从 RxJava 迁移到 Kotlin/Anko Corountines,我想知道我是否正在做最好的(第一个)方法:
fun getPopulationList() {
val ref = asReference()
async(UI) {
try {
ref().setCurrentState(ViewState.State.LOADING)
val background = bg {
repository.populationResponse().execute().body()
}
ref().let {
it.response = background.await()
it.mvpView?.onGetData(it.response)
it.setCurrentState(ViewState.State.FINISH)
}
} catch (e: Exception) {
e.printStackTrace()
ref().mvpView?.onError(e)
}
}
}
我正在使用 MVP 架构,其中我的 Presenter 基类有一个 CompositeSubscription 并且在 onDestroy 的片段或活动方法中简单地取消订阅并清除 CompositeSubscription 对象。但我想知道 Anko Coroutines 的 asReference() 函数是否也一样,不需要保存 Deferred<T> 的列表,然后对其进行迭代并一一取消。
顺便说一句,如果我添加一个Thread.sleep(5000) 来模拟一个大事务并销毁片段,我可以在 logcat 中看到 HTTP 响应,即使在片段不可见/被破坏而 RxJava 不会发生,所以我想我没有正确使用。
更新
fun getPopulationList() {
val ref = asReference()
job = launch(UI) {
try {
ref().setCurrentState(ViewState.LOADING)
val background = bg {
Thread.sleep(5000) //simulate heavy IO
if (isActive) {
repository.populationResponse().execute().body()
} else {
return@bg null
}
}
ref().let {
it.response = background.await()
it.mvpView?.onGetData(it.response)
it.setCurrentState(ViewState.FINISH)
}
} catch (e: Exception) {
RestHttpExceptionHandler().handle(UI, e, ref())
}
}
}
我可以在 onDestroy() 方法中调用 job.cancel() 时取消协程,但要使其正常工作,我必须检查作业是否处于活动状态,并且转换为 if/else 和返回或不数据.有没有更好的方法在作业被取消时返回?
【问题讨论】:
标签: android kotlin kotlinx.coroutines anko