skip to content
Alvin Lucillo

Observables, subscription, and operators

/ 2 min read

💻 Tech

RxJS is one of the ways to handle asynchronous operations with data transformations. Observables handle asynchronous operations like multiple data streams. In the example below, it emits an array of objects to simulate an API call. Operators like map allow data transformation of data streams. Finally, the observables can be used by other parts of an app by subscribing to them.

import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface Employee {
    id: number;
    name: string;
    departmentId: number;
}

type Employees = Employee[]

displayEmployees(); // main entry point

function displayEmployees() {
    const observable = getEmployeesByDepartment(1);

    // Subscribe to the observable
    observable.subscribe({
        next: x => console.log('Transformed value: ', x),
        error: err => console.error('Something went wrong: ', err),
        complete: () => console.log('Done'),
    });
}

function getEmployeesByDepartment(departmentId: number): Observable<Employees> {
    const employeeObservable = getAllEmployeesAPI()

    // Transform the observable with operators
    return employeeObservable.pipe(
        map((employees: Employees) => employees.filter(emp => emp.departmentId === departmentId))
    );

}

function getAllEmployeesAPI(): Observable<Employees> {
    // Simulates actual API call
    const observable = new Observable<Employees>(subscriber => {
        const employees: Employees = [
            {
                id: 1,
                departmentId: 1,
                name: 'user1',
            },
            {
                id: 2,
                departmentId: 2,
                name: 'user2',
            },
            {
                id: 3,
                departmentId: 1,
                name: 'user3',
            }
        ];
        subscriber.next(employees);
        subscriber.complete();
    });

    return observable
}