Search code examples
rxjsangular-formsrxjs-observables

Updating value of an observable without applying the subscribe


I subscribe to an Observable with a pairwise pipe in order to get previous and new value.

But sometime I would like to tell the Observable that the value has been updated without applying the subscribe function. It will ensure that the previousValue is always updated but without always applying the subscribe function.

// Listen to FomControl -> update value variable.
this.valueChangesSubscription = this.control.valueChanges
    .pipe(startWith(this.defaultValue), pairwise())
    .subscribe(async ([previousValue, newValue]) => {
        // Do something
    });

I update the value of the formControl and sometime emitting the event, sometimes not:

this.control.setValue(formattedValue, { emitEvent });

But I would like that even if the event is not emitted, the previousValue of the subscribe function will be the real previousValue and not juste the latest emitted one.

Thank you.


Solution

  • You can try the filter operator to filter the subscribed result

    private myBooleanValue = false;
    
    // Listen to FomControl -> update value variable.
    this.valueChangesSubscription = this.control.valueChanges
        .pipe(
           startWith(this.defaultValue), 
           pairwise(),
           // It will never emit a value to subscribe since its false
           filter(([previousValue, newValue]) => this.myBooleanValue),
         )
        .subscribe(async ([previousValue, newValue]) => {
            // Do something
        });