花了一天讨论coroutine的写法,主要问题还是错误处理和生命周期处理。毫无疑问,coroutine的代码更加清晰易懂。
//错误处理
private val exceptionHandler: CoroutineContext = CoroutineExceptionHandler { _, throwable ->
presenter.showFailView()
}
//Coroutine写法
private fun getCountryCodeData() = launch(UI + exceptionHandler, parent = AndroidJob(this)) {
presenter.showLoading()
val deferred = service.getCountryCode()
val data = deferred.await()
presenter.setSelectedCountryCode(selectedCountryCode)
presenter.setData(data)
presenter.hideLoading()
}
//项目中RxJava写法
private fun getCountryCodeData() {
service.getCountryCode().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDispose.autoDisposable(this))
.subscribe({
presenter.setSelectedCountryCode(selectedCountryCode)
presenter.setData(it)
presenter.hideLoading()
}, {
presenter.showFailView()
})
}
使用Uber的AutoDispose库绑定生命周期,主要处理协程的cancel。谷歌的LifeCycle库也不错,用起来特别方便,但实现太hack了,用无UI的Fragment实现生命周期的逻辑的抽取和监听,虽然接口非常漂亮,实在接受不能。
class AndroidJob(lifecycle: LifecycleScopeProvider<InteractorEvent>) : Job by Job() {
init {
lifecycle.lifecycle().filter { it == InteractorEvent.INACTIVE }
.subscribe {
cancel()
}
}
}