Search code examples
angularrxjs6angular-pipe

Angular async pipe reduces stream value rather than displays latest emission


My useage of mergeMap seems to reduce the boolean stream down to one value, because

<button [disabled]="!(canRequestPricing$ | async)"

canRequestPricing$ | async should be true, but if the first emission is false, it is false.

public canRequestPricing$ = new BehaviorSubject<boolean>(false);


public ngOnInit(): void {
    this.canRequestPricingSubscription = this.canRequestPricing$.pipe(
        mergeMap(() => this.mappedItem.canRequestPricing()),
        take(1),
        mergeMap((canRequestPricingFromApi) => {
            const can = this.canRequestPricing() && canRequestPricingFromApi;
            return of(can);
        })).subscribe();
}

since the emitter initialises with false, the (canRequestPricing$ | async) amounts to false. When I initialise it with true then (canRequestPricing$ | async) amounts to true.

const can = this.canRequestPricing() && canRequestPricingFromApi; always is true which is correct, and I just need the initialsed false of public canRequestPricing$ = new BehaviorSubject<boolean>(false); to not effect the final value.

I want the behaviour to be that (canRequestPricing$ | async) amounts to whatever the last emission was. How do I get that behaviour?


Solution

  • If I understood correctly, canRequestPricing$ is dependent on this.canRequestPricing() and this.mappedItem.canRequestPricing().

    this.mappedItem.canRequestPricing().pipe(
      take(1),
      map(canRequestPricingFromApi => this.canRequestPricing() && canRequestPricingFromApi)
    ).subscribe(can => {
      this.canRequestPrincing$.next(can);
    })