gothaf
gothaf

Reputation: 228

Subscribing to valueChanges with combineLatest

I am trying to get the total price of a product by multiplying its quantity with its value. When I select the product from my list it has an initialValue and an initialQuantity then I subscribe to the valueChanges of both to make the calculations like so:

        let initialQuantity = this.items.at(lastIndex).get("quantity").value;
        let initialValue = this.items.at(lastIndex).get("productValue").value;

        this.quantity$ = this.items.at(lastIndex).get("quantity").valueChanges;
        this.productValue$ = (this.items.at(lastIndex).get("productValue").valueChanges;

         combineLatest(this.quantity$, this.productValue$)
            .pipe(
                startWith([initialQuantity, initialValue]),
                takeUntil(this._destroy)
            )
            .subscribe(([quantity, productValue]) => {

                let totalPrice = quantity * productValue;

                this.items.at(lastIndex).get("totalPrice").setValue(totalPrice);
            });
});

The thing is that I have to change both values for combineLatest to start emitting even if I have set the initial values with startWith and the first result is showing correctly. So if I change only the quantity or only the product value, nothing happens. What am I doing wrong?

Upvotes: 1

Views: 492

Answers (1)

Andrei Gătej
Andrei Gătej

Reputation: 11944

I think you could do this:

combineLatest(
  this.quantity$.pipe(startWith(initialQuantity)), 
  this.productValue$.pipe(startWith(initialValue))
)
  .pipe(
    map(([quantity, value]) => quantity * value)
    takeUntil(this._destroy)
  ).subscribe(/* ... */)

I'd also suggest not 'bloating' your subscribe callback with too much logic when that can be done with the operators(e.g: map from above)

Upvotes: 2

Related Questions