Search code examples
rxjsrxjs6

Tap after observable has been subscribed


Is there a way to add more operations to an observable that has already been subscribed? I tried the below code, which doesn't work, as the One more tap after subscribe part is not executed (code is here)

import { of, timer } from 'rxjs';
import { tap, map, take } from 'rxjs/operators';

const source = timer(1000, 1000);
//transparently log values from source with 'do'
const example = source.pipe(
  take(3),
  tap(val => console.log(`BEFORE MAP: ${val}`)),
  map(val => val + 10),
  tap(val => console.log(`AFTER MAP: ${val}`))
);

//'do' does not transform values
//output: 11...12...13...14...15
const subscribe = example.subscribe(val => console.log(val));

example.pipe(
  tap(val => console.log(`One more tap after subscribe: ${val}`))
);

The use cas I have in mind is where for example I make an http call, and more than one service needs to be updated with the reponse of the call.


Solution

  • I will take this as what you ultimately want to achieve

    The use cas I have in mind is where for example I make an http call, and more than one service needs to be updated with the reponse of the call.

    const onExampleCalled=new Subject();
    // listen to example called
    onExampleCalled.subscribe(console.log)
    example.pipe(tap(result=>onExampleCalled.next(result)).subscribe()