Calling subscribe inside subscribe

281 Views Asked by At

There are two variables depending on each other (color and pictures). Depending means following: When the variable color has the value of'BLUE' I want to filter all the pictues which have the color blue and so on. Variable pictures is a subject with a service/backend call:

this.colorSubject.subscribe((color) => {
      subject.switchMap((searchTerm: string) => serviceCall(searchTerm, color) ).subsribe(...)
});

For that I need to listen for the change of the color variable and then calling the above line of code. But this causes multiple calls of the service.

Any ideas how to handle this issue?

1

There are 1 best solutions below

1
On

If I am understanding you correctly, you need a third stream that represents the joined result of color and pictures. Let's call it filteredPictures$. That stream should utilize color and pictures using combineLatest. Now, if either of the streams change, filteredPictures$ will notify all subscribers of the new value.

const {
  Subject,
  from,
  combineLatest
} = rxjs;
const {
  withLatestFrom,
  switchMap
} = rxjs.operators;

const color = new Subject();
const pictures = new Subject();

function service(searchTerm = "house", colorTerm = "green") {
  return Promise.resolve([`${searchTerm}.jpg`, `${colorTerm}.png`]);
}

const color$ = color.asObservable();
const pictures$ = pictures.asObservable();
const filteredPictures$ = combineLatest(
  pictures$,
  color$
).pipe(switchMap(([searchTerm, colorTerm]) => from(service(searchTerm, colorTerm))));

filteredPictures$.subscribe(console.log);

pictures.next("water");
setTimeout(() => {
  color.next("yellow");
  setTimeout(() => {
    pictures.next("helicoptor");
    setTimeout(() => {
      color.next("red");
    }, 1000);
  }, 1000);
}, 1000);
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>