RxJS 运算符仅在第一个源为空时订阅新源?
RxJS operator to subscribe to a new source only if the first source is empty?
我正在尝试弄清楚如何使用 RxJS 6 检查缓存中的值,并且仅当在缓存中找不到该值时,才从数据库中请求该值。理想情况下,我可以将从数据库接收到的值添加到缓存中。
到目前为止,我已经查看了 race
,但这将同时请求两者并取其先响应。如果该值在缓存中可用,我不想从数据库请求。 flatMap
好像有同样的问题?
我知道 defaultIfEmpty
但它只提供默认的 值 ,而不是订阅新的 Observable 并发出这些值。
我认为您在这里寻找的运算符是 defer
,根据工厂创建函数,它在订阅时间之前不会实际创建被订阅的可观察对象。您还没有发布代码,但以伪代码形式它看起来像这样:
const getValue$ = (value: number) => defer(() => {
const cachedValue = checkCache(value);
if (cachedValue) {
return of(cachedValue);
} else {
return this.db.get(value).pipe(
mergeMap(dbReturnedValue => addToCache(dbReturnedValue))
);
}
});
// later in code:
getValue$(testValue).subscribe(
data => doSomething(data),
err => processError(err)
);
我正在尝试弄清楚如何使用 RxJS 6 检查缓存中的值,并且仅当在缓存中找不到该值时,才从数据库中请求该值。理想情况下,我可以将从数据库接收到的值添加到缓存中。
到目前为止,我已经查看了 race
,但这将同时请求两者并取其先响应。如果该值在缓存中可用,我不想从数据库请求。 flatMap
好像有同样的问题?
我知道 defaultIfEmpty
但它只提供默认的 值 ,而不是订阅新的 Observable 并发出这些值。
我认为您在这里寻找的运算符是 defer
,根据工厂创建函数,它在订阅时间之前不会实际创建被订阅的可观察对象。您还没有发布代码,但以伪代码形式它看起来像这样:
const getValue$ = (value: number) => defer(() => {
const cachedValue = checkCache(value);
if (cachedValue) {
return of(cachedValue);
} else {
return this.db.get(value).pipe(
mergeMap(dbReturnedValue => addToCache(dbReturnedValue))
);
}
});
// later in code:
getValue$(testValue).subscribe(
data => doSomething(data),
err => processError(err)
);