Чтобы добиться этого, я немного изменил ваши cache$
и request$
, чтобы идентифицировать наблюдаемое:
const cache$ = getFromCacheLazy().pipe(
map(cache => {
return {source: 'cache', value: cache};
})
);
const request$ = executeRequest().pipe(
map(request => {
return {source: 'request', value: request};
})
);
Я оставил concat
, как и вы.
И затем я применил функцию withLatestFrom
, чтобы получить последнее значение. Если последнее полученное значение получено из request$
, я возвращаю его, иначе я объединяю наблюдаемые, чтобы вернуть значение cache$
, и подождите не менее 500 мс, чтобы выдать request$
:
const $subscribeDelayed = timer(subscriptionDelay)
.pipe(
withLatestFrom(cacheAndRequest$), // Provide the latest value from cacheAndRequest$
switchMap(res => {
// if request$ is already completed at the time of subscription, cache$ value is ignored
// else cache$ is emitted and request$ is emitted after at least 500ms
return res[1].source === 'request'
? of(res[1].value)
: concat(
of(res[1].value),
request$.pipe(
delay(500),
map(res => res.value)
)
);
}),
tap(res => console.log(res)),
);
См. мой рабочий пример с Stackblitz .