类似的寻找答案downvoted。但是我认为我可以证明我在有限情况下的建议。
确实,可观察对象没有当前值,但通常情况下它将具有立即可用的值。例如,对于redux / flux / akita存储库,您可以根据多个可观察对象向中央存储库请求数据,并且该值通常可以立即获得。
如果是这种情况,那么当您输入时subscribe
,该值将立即返回。
假设您有一个服务调用,并且在完成后希望从商店中获取某商品的最新价值,这可能不会发出:
您可以尝试执行此操作(并且应尽可能将内容保留在“管道内”):
serviceCallResponse$.pipe(withLatestFrom(store$.select(x => x.customer)))
.subscribe(([ serviceCallResponse, customer] => {
// we have serviceCallResponse and customer
});
问题在于它将阻塞直到辅助可观察对象发出一个值,该值可能永远不会出现。
我发现自己最近仅在值立即可用时才需要评估一个可观察值,更重要的是,我需要能够检测它是否不存在。我最终这样做:
serviceCallResponse$.pipe()
.subscribe(serviceCallResponse => {
// immediately try to subscribe to get the 'available' value
// note: immediately unsubscribe afterward to 'cancel' if needed
let customer = undefined;
// whatever the secondary observable is
const secondary$ = store$.select(x => x.customer);
// subscribe to it, and assign to closure scope
sub = secondary$.pipe(take(1)).subscribe(_customer => customer = _customer);
sub.unsubscribe();
// if there's a delay or customer isn't available the value won't have been set before we get here
if (customer === undefined)
{
// handle, or ignore as needed
return throwError('Customer was not immediately available');
}
});
请注意,对于上述所有内容,我都在使用subscribe
以获得值(如@Ben讨论的那样)。.value
即使使用,也不会使用属性BehaviorSubject
。