Home > Software engineering >  How to get the last value from all Observables when any of them emit a new value?
How to get the last value from all Observables when any of them emit a new value?

Time:12-28

I have N Observables/BehaviourSubjects, bound to N select fields. Which is the best approach using RxJS to get the last value from all observables when one of them emit a new value?

I'm developing a filter, so when one filter changes, I'll need to call backend with all filters selected on the screen.

CodePudding user response:

The best approach is to use a combineLatest when you need a value from two or more reactive structures. It is an operator that combines two or more observables and generates values for all of them every time one of the observables generates a value. Here is an example from the RxJs documentation:

const timerOne$ = timer(1000, 4000);
const timerTwo$ = timer(2000, 4000);
const timerThree$ = timer(3000, 4000);

combineLatest([timerOne$, timerTwo$, timerThree$])
   .subscribe(([timerValOne, timerValTwo, timerValThree]) => {
      console.log(
      `Timer One Latest: ${timerValOne},
      Timer Two Latest: ${timerValTwo},
      Timer Three Latest: ${timerValThree}`
    );
  }
);

And here is a working example: https://playcode.io/1046311

Hope I helped you! See https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest for more information.

CodePudding user response:

Behavior Subject can be used to get the last value from that observable

public foo$: BehaviorSubject<any> = new BehaviorSubject(null);
public bar$: BehaviorSubject<any> = new BehaviorSubject(null);

public listenAll() {
  this.foo$.subscribe((val) => {
    console.log(value) // emited new value of foo
    console.log(this.bar$.value) // last emitted value of bar$
  });

  this.bar$.subscribe((val) => {
    console.log(value) // emited new value of bar
    console.log(this.foo$.value) // last emitted value of foo$
  })
}

CodePudding user response:

You can use combineLatest operator to combine the latest values from all the observables. And depending on the value change you can call the backend service.

//when one of the observable emits, it will emit the latest values as an array
const combined = combineLatest(filter1$, filter2$, filter3$);
const subscription = combined.subscribe(
  ([value1, value2, value3]) => {
// your other logic
});
  • Related