I want to execute tap() only when i get the first emitted value
Something like:
Observable
.pipe(
tap(() => { /* execute only when I get the first emitted value */ })
)
.subscribe(() => {
// .....
})
RxJS tap() operator is a utility operator that returns an observable output that is identical to the source observable but performs a side effect for every emission on the source observable.
The RxJS first() operator is generally used when you are only interested in the first item emitted by the source observable or the first item that meets some criteria. In this case, you can use this operator to filter the Observable.
pipe() can be called on one or more functions, each of which can take one argument ("UnaryFunction") and uses it to return a value. It returns a function that takes one argument, passes it to the first UnaryFunction, and then passes the result to the next one, passes that result to the next one, and so on.
A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. It is a pure operation: the previous Observable stays unmodified. A Pipeable Operator is essentially a pure function which takes one Observable as input and generates another Observable as output.
You can use the index in map operators like concatMap
. Unlike other approaches this is totally flexible about the chosen index. Let's say if you want tap on 2nd emission index === 1
or any predicate like index % 2 === 0
// these are because of using rxjs from CDN in code snippet, ignore them
const {of, interval} = rxjs;
const {take, tap, concatMap} = rxjs.operators;
// main code
const stream = interval(250).pipe(take(4))
stream.pipe(
concatMap((value, index) => index === 0
? of(value).pipe(
tap(() => console.log('tap'))
)
: of(value)
)
)
.subscribe(x => console.log(x));
<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/rxjs.umd.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With