3
votes

I have a RXJS function that will create an empty Observable, tap into the result and return that new observable. I want the observable to always run the tap so I noop subscribe (in the real case it might not ever be subscribed to).

function that() {
  let obs = of({});
  obs = obs.pipe(tap(() => console.log('here')))
  obs.subscribe();
  return obs;
}

const res = that();
res.subscribe(() => console.log('finished'))

If you run this code on StackBlitz, you will notice that here is fired twice. The output looks like this:

 here
 here
 finished

I've tried several different approaches but I can't ever seem to get it to work where it doesn't emit twice.

2

2 Answers

0
votes

You subscribe TWICE:

function that() {
    let obs = of({});
    obs = obs.pipe(tap(() => console.log('here')))
    obs.subscribe(); // first subscription
    return obs;
}

const res = that();
res.subscribe(() => console.log('finished')) // second subscription

This is the same observable you subscribe to, once in the function, then on the returned value.

Just don't subscribe in the function

function that() {
    let obs = of({});
    obs = obs.pipe(tap(() => console.log('here')))
    return obs;
}

const res = that();
res.subscribe(() => console.log('finished')) // subscribe from here only

See the updated StackBlitz.

0
votes

Is it just a case of only tapping only the inner subscription?

function that() {
  let obs = of({});
  obs.pipe(tap(() => console.log('here'))).subscribe();
  return obs;
}

const res = that();
res.subscribe(() => console.log('finished'))