我已经在我的项目中使用RxJava大约一年了.随着时间的推移,我变得非常喜欢它 - 现在我想的可能太多了......
我现在写的大多数方法都有某种形式的Rx,这很棒!(直到它不是).我现在注意到一些方法需要大量工作来组合不同的可观察生产方法.我觉得虽然我理解我现在写的东西,但下一个程序员将很难理解我的代码.
在我到达底线之前,让我直接从我在Kotlin的代码中给出一个例子(不要深入研究它):
private fun <T : Entity> getCachedEntities(
getManyFunc: () -> Observable<Timestamped<List<T>>>,
getFromNetwork: () -> Observable<ListResult<T>>,
getFunc: (String) -> Observable<Timestamped<T>>,
insertFunc: (T) -> Unit,
updateFunc: (T) -> Unit,
deleteFunc: (String) -> Unit)
= concat(
getManyFunc().filter { isNew(it.timestampMillis) }
.map { ListResult(it.value, "") },
getFromNetwork().doOnNext {
syncWithStorage(it.entities, getFunc, insertFunc, updateFunc, deleteFunc)
}).first()
.onErrorResumeNext { e -> // If a network error occurred, return the cached data and the error
concat(getManyFunc().map { ListResult(it.value, "") }, error(e))
}
Run Code Online (Sandbox Code Playgroud)
简而言之,它的作用是: