-1

I want to have multiple observables scheduled consistently with forkJoin, but want to subscribe each of them individually, like below.

const ox = http.get('x');
const oy = http.get('y');
const all = interval(1000).pipe(
  switchMap(
    () => forkJoin(ox, oy)
  );
);

// component x
const sx = ox.subscribe((x) => { showX(x); });
// component y
const sy = oy.subscribe((y) => { showY(y); });
// Another component
const sAll = all.subscribe(([x, y]) => { doStuffThatNeedsBothXY(x, y); });

What would be a best way to do this? I want to keep ox and oy type as Observable, instead of using other techniques like piping side effect (tap) at all.

tink
  • 39
  • 1
  • 6

1 Answers1

0

It seems unnecessary to subscribe to each separate stream and subscribe to both.

You could do something like this:

  sAll = combineLatest(this.toDos$, this.posts$)
    .pipe(
      tap(([todos, posts]) => {
        this.todos = todos;
        this.posts = posts;
      })
    )
    .subscribe(() => console.log("subscribe"));

Using combineLatest automatically subscribes to each of the streams and gives you access to both.

NOTE: If you subscribe to ox and subscribe to a combination of ox and another stream, you will subscribe to the stream twice AND issue the HTTP request for x a second time. You can try that out in my sample Stackblitz.

I have an example Stackblitz here:

https://stackblitz.com/edit/angular-todos-posts-noasynpipe-deborahk

Or looking at it with your variables:

  sAll = combineLatest(ox, oy)
    .pipe(
      tap(([x, y]) => {
        showX(x);
        showY(y);
        doStuffThatNeedsBothXY(x,y);
      })
    )
    .subscribe(() => console.log("subscribe"));

If that doesn't match your requirements, could you be mores specific on the use-case for needing all three subscriptions?

DeborahK
  • 57,520
  • 12
  • 104
  • 129