📜  do and tap operator rxjs (1)

📅  最后修改于: 2023-12-03 15:30:31.265000             🧑  作者: Mango

Do and Tap Operator in RxJS

The do and tap operators in RxJS are used for performing side effects in an observable stream without modifying the stream itself.

What is Side Effect?

A side effect in programming is any effect caused by a function or method that is not directly related to its output. Side effects can be desirable, like logging or caching, or undesirable, like changing variables in another scope or modifying a shared state.

In RxJS, side effects often involve performing actions outside of the observable stream. For example, logging to the console, making a network request, or updating the DOM.

Using the do Operator

The do operator in RxJS is used to perform a side effect on each value emitted by an observable stream. Here's how you can use it:

import { of } from 'rxjs';
import { tap } from 'rxjs/operators';

const source$ = of(1, 2, 3);

source$.pipe(
  tap(value => console.log(`Value emitted: ${value}`))
)
.subscribe();

In this example, the of operator creates an observable stream of numbers. The tap operator receives each value emitted by the stream and logs it to the console.

Output:

Value emitted: 1
Value emitted: 2
Value emitted: 3

Notice that the original observable stream is not modified by the tap operator. It simply performs the side effect of logging each value emitted.

Using the tap Operator

The tap operator is an alias for the do operator. It is included in RxJS for convenience, as some developers find the name tap more intuitive when performing side effects. Both operators behave the same way and can be used interchangeably.

import { of } from 'rxjs';
import { do } from 'rxjs/operators';

const source$ = of(1, 2, 3);

source$.pipe(
  do(value => console.log(`Value emitted: ${value}`))
)
.subscribe();

This code produces the same output as the previous example, logging each value emitted by the observable stream.

Conclusion

In summary, the do and tap operators in RxJS are used to perform side effects on an observable stream without modifying the stream itself. They are useful for logging, making network requests, or performing other actions outside of the observable stream. Remember that side effects can have a significant impact on the behavior of your program, so use them consciously and as needed.