【发布时间】:2016-06-05 19:25:50
【问题描述】:
我有一种情况,通过获取 Item 对象,应该会发生以下三件事之一:
- 如果缓存中不存在该项(a.k.a 为 null),则从
api1和api2加载数据,合并数据并返回Observable。 - 如果该项目存在于缓存中,但缺少某部分,则从
api2加载数据,并将其与缓存中已有的数据合并 - 如果缓存中的所有数据都可用,只需返回即可。
到目前为止,这是我想出的最好的:
val cacheObservable = cache.fetchItem(itemId);
val api1Observable = api1.fetchItem(itemId);
val api2Observable = api2.fetchItem(itemId);
val resultObservable = cacheObservable!!.flatMap { item: Item? ->
if (item == null) {
/* Get the item data, and the full text separately, then combine them */
Observable.zip(api1Observable, api2Observable, { itemData, itemText ->
itemData.apply { text = itemText }
});
} else if (item.text.isNullOrEmpty()) {
/* Get the full text only, then add it to the already cached version */
cacheObservable.zipWith(api2Observable, { cachedItem, itemText -> cachedItem.apply { text = itemText; } });
} else {
/* if the data and the full text are provided, simply return */
Observable.just(item);
}
}.doOnNext { item -> cache.saveOrUpdateItem(item); }
return resultObservable;
到目前为止,这工作正常,但我一直想知道,是否有更声明的方式来实现相同的效果。欢迎提出建议。
【问题讨论】:
-
您的
fetchItem函数可以返回错误而不是null,因此您可以使用错误处理运算符而不是检查空值。
标签: android rx-java kotlin observable