shuke
shuke

Reputation: 46

Does rxjs observable tap happen before subscription?

I've been looking through the documents about rxjs observable tap and subscribe, and it seems that tap is for the side effects that you want for multiple subscriptions, while subscribe should be used specifically for a single subscription. However, I'm wondering in the case when both are used, which one gets executed first?

I did some experiment and found it was tap, but want to confirm and wonder if there are any official documents for it.

Upvotes: 0

Views: 1760

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21638

Have you stuck a few logs in the pipe?

const { of, tap } = rxjs;

const obs$ = of('hello').pipe(
  tap(val => { console.log(`${val} from tap`); })
);

console.log('No subscription so no values flowing down the pipe yet');

obs$.subscribe(val => { console.log(`${val} from subscribe`); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.8.0/rxjs.umd.min.js" integrity="sha512-v0/YVjBcbjLN6scjmmJN+h86koeB7JhY4/2YeyA5l+rTdtKLv0VbDBNJ32rxJpsaW1QGMd1Z16lsLOSGI38Rbg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

An observable is a function that sets up for observation. That chain is triggered by subscribing, the first thing that starts the chain is the act of calling subscribe. As the observable emits a value it will be piped through all the pipe functions. The next function that was passed into the subscribe call will be called as the final pipe in the chain emits a value.

If you want a good understanding of how things work the best documentation is the source code on Github. Looking at the source code for open source projects is a great learning tool.

Upvotes: 2

Antoniossss
Antoniossss

Reputation: 32507

tap is just a part of rx pipeline in which subscriber is at the end of that pipeline, therefore tap will be first

Keep in mind that (unless made otherwise with proper operator) every subscription creates brand new pipeline.

Upvotes: 2

Related Questions