0

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?

myanmar
  • 81
  • 1
  • 2
  • 11
  • Can you post a full reproduction? Also what's _exactly_ the issue? You say you're duplicating code but I don't see anything duplicate here. Can we see how you _made_ it work and then we could help generalize it? – Lazar Ljubenović Sep 27 '18 at 16:48
  • is the color a stream as well? if not - it should be. and then you can simply switchMap from the color observable to the observable described by you – Patrick Kelleter Sep 27 '18 at 16:49
  • I pasted the code. – myanmar Sep 27 '18 at 17:10

1 Answers1

0

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>
zero298
  • 25,467
  • 10
  • 75
  • 100
  • Yes, that is what I am searching for. But there is still one point: At the beginning there is no service call? – myanmar Sep 28 '18 at 06:54