Search code examples
angularrxjsobservable

Angular - How to combine multiple "valueChanges" observables into one


How can I combine the following subscriptions into one?

    this.form.get("type").valueChanges.subscribe(() => {
        this.calcFinalTransports();
    })
    this.form.get("departure").valueChanges.subscribe(() => {
        this.calcFinalTransports();
    })
    this.form.get("destination").valueChanges.subscribe(() => {
        this.calcFinalTransports();
    })
    this.form.get("stations").valueChanges.subscribe(() => {
        this.calcFinalTransports();
    })

Solution

  • You have a few choices depending on what output you expect. You may want to read this article:

    If you just want to get notified whenever any of the value changes use merge:

    import {merge} from "rxjs/observable/merge";
    
    merge(
        this.form.get("type").valueChanges,
        this.form.get("departure").valueChanges,
        this.form.get("destination").valueChanges
        this.form.get("stations").valueChanges
    ).subscribe(() => this.calcFinalTransports());