side effect


In programming, a side effect is any action that interacts with the outside world or modifies the state of the application in a way that is observable outside the function or operator itself.

some common examples of side effects you might perform within a tap() operator

  • Logging: For monitoring or debugging, recording data to the console. Though it communicates with the console, or "outside world," this does not affect the data running through the observable.

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

of(1, 2, 3).pipe(
     tap(value => console.log(`Emitted value: ${value}`)), 
     // Side effect: logging
).subscribe(data => console.log(`Received data: ${data}`));

  • Saving Data: Initiating an HTTP request to store data on a server. This changes the condition of your back end system.

 

import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
class DataService {
 constructor(private http: HttpClient) {}

 saveData(value: number) {
   return this.http.post('/api/data', { value });
 }
}

// ... in your component or service
of(42).pipe(
   tap(value => this.dataService.saveData(value).subscribe()), 
   // Side effect:  making an HTTP request
).subscribe(response => console.log('Save operation initiated'));

  • Displaying messages/notifications to the user or altering the visual state of the application

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

class NotificationService {
   showNotification(message: string) {
       alert(message);
    }
}


const notificationService = new NotificationService();

of('Processing...', 'Complete!').pipe(
     tap(message => notificationService.showNotification(message)), 
     // Side effect: showing a notification
).subscribe();

 


Related Question