observable from a promise
observable from a promise allows you to convert a JavaScript Promise into an Observable, enabling seamless integration with Angular's reactive programming. This is particularly useful for handling asynchronous operations.Example
import { from, Observable } from 'rxjs';
const promise = new Promise<number>((resolve) => {
setTimeout(() => resolve(42), 1000);
});
const observableFromPromise: Observable<number> = from(promise);
observableFromPromise.subscribe((value) => {
console.log(`Value from Observable: ${value}`);
});
observable from a counter
observable from a counter creates an Observable that emits a sequence of numbers, which can be useful for various scenarios like implementing timers or progress indicators.Example
import { interval, Observable } from 'rxjs';
const counterObservable: Observable<number> = interval(1000);
counterObservable.subscribe((value) => {
console.log(`Counter Value: ${value}`);
});
observable from an event
observable from an event lets you create an Observable that emits events from a DOM element or any other event source. This is commonly used for handling user interactions.Example
import { fromEvent, Observable } from 'rxjs';
const button = document.getElementById('myButton');
const clickObservable: Observable<MouseEvent> = fromEvent(button, 'click');
clickObservable.subscribe((event) => {
console.log('Button Clicked:', event);
});
Map operator
Map operator is used to transform the emitted values of an Observable into a new format.Example
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
const source = of(1, 2, 3);
const mappedObservable = source.pipe(map((value) => value * 10));
mappedObservable.subscribe((value) => {
console.log(`Mapped Value: ${value}`);
});
filter() operator
filter() operator is employed to selectively emit values from an Observable based on a given condition.Example
import { of } from 'rxjs';
import { filter } from 'rxjs/operators';
const source = of(1, 2, 3, 4, 5);
const filteredObservable = source.pipe(filter((value) => value % 2 === 0));
filteredObservable.subscribe((value) => {
console.log(`Filtered Value: ${value}`);
});
concat() operator
concat() operator is used to concatenate multiple Observables into a single Observable, emitting values in a sequential manner.Example
import { concat, of } from 'rxjs';
const observable1 = of(1, 2);
const observable2 = of(3, 4);
const concatenatedObservable = concat(observable1, observable2);
concatenatedObservable.subscribe((value) => {
console.log(`Concatenated Value: ${value}`);
});
flatMap() operator
flatMap() operator is employed to flatten nested Observables and merge their emissions into a single stream.Example
import { of } from 'rxjs';
import { flatMap } from 'rxjs/operators';
const source = of(1, 2, 3);
const mappedObservable = source.pipe(flatMap((value) => of(value, value * 2)));
mappedObservable.subscribe((value) => {
console.log(`FlatMapped Value: ${value}`);
});
Standalone pipe function
The standalone pipe function is used to apply multiple operators to an Observable in a concise manner, allowing for a more organized and readable code structure.Example
import { of } from 'rxjs';
import { map, filter } from 'rxjs/operators';
const source = of(1, 2, 3);
const transformedObservable = source.pipe(
filter((value) => value % 2 === 0),
map((value) => value * 10)
);
transformedObservable.subscribe((value) => {
console.log(`Transformed Value: ${value}`);
});
catchError operator
catchError operator is used to gracefully handle errors that occur in an Observable stream.Example
import { throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
const source = throwError('This is an error');
const errorHandledObservable = source.pipe(
catchError((error) => of(`Error Handled: ${error}`))
);
errorHandledObservable.subscribe((value) => {
console.log(value);
});
Retry failed observable
Retry failed observable can be applied to retry an Observable a specified number of times in case of failures.Example
import { interval, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
const source = interval(1000).pipe(
catchError((error) => {
console.log(`Error: ${error}`);
return throwError('Retrying...');
}),
retry(3)
);
source.subscribe(
(value) => console.log(`Value: ${value}`),
(error) => console.error(`Final Error: ${error}`)
);
Naming Observables
When naming Observables, it's a good practice to use clear and descriptive names that reflect the data or events they represent. This helps improve code readability and maintainability.Example
import { Observable } from 'rxjs';
const userData$: Observable<User[]> = getUsersFromApi();
const buttonClick$: Observable<MouseEvent> = fromEvent(button, 'click');
const timer$: Observable<number> = interval(1000);