因此,我正在将一个示例应用程序从 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
目的。但我想知道是否asReference()
Anko 协程中的函数执行相同的操作,并且无需保存列表Deferred<T>
然后迭代并一一取消。
顺便说一句,如果我添加一个Thread.sleep(5000)
为了模拟大事务并销毁片段,即使片段不可见/被销毁,我也可以在 logcat 中看到 HTTP 响应,而使用 RxJava 不会发生这种情况,所以我认为我没有正确使用。
UPDATE
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())
}
}
}
我可以在调用时取消协程job.cancel()
in onDestroy()
方法,但为了使其工作,我必须检查作业是否处于活动状态,并将其转换为 if/else 以及返回或不返回数据。作业取消后有没有更好的方法来退货?
正如你所看到的作为参考() https://github.com/Kotlin/anko/blob/master/anko/library/generated/coroutines/src/weakReferenceSupport.ktsource 它只不过是一个弱引用和调用方法来获取抛出的引用CancellationException
当对象被收集时。它不会执行任何取消操作的操作。只是意识到收集的对象.
所以你需要保留一个参考Job https://github.com/Kotlin/kotlinx.coroutines/blob/master/core/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/Job.kt或其子类型来取消操作。
launch
协程构建器来自kotlinx.协程 https://github.com/Kotlin/kotlinx.coroutines返回一个 Job 实例。这是一个例子:
private lateinit var job: Job
private fun startCoroutines() {
val ref = asReference()
job = launch(UI) {
try {
val deferred = async(parent = coroutineContext[Job]) {
//do some work
result//return
}
ref().setData(deferred.await())
} catch (e: Exception) {
e.printStackTrace()
}
}
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
Notes:
1-当结果类型不重要时launch
可以用来代替async
.
2-要在子协程中取消,您必须创建父/子作业层次结构。我通过了父母(launch
) Job
引用子协程(异步)来实现这一点。
3- as 取消是合作的取消实现必须以异步方式完成(参见示例here https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#cancellation-and-timeouts).
3- job.cancel()
用于 onDestroy 取消作业,它是子异步的。这可以在 Presenter 中以 MVP 模式完成。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)