Playing around with RxJS

1 minAngular

I have never really worked with the library RxJS. As I understand it, it is used to handle asynchronous and event-based operations. I want to start looking into observables, observers and subscriptions. I will make a really simple example with a button.

interface User {
    id: number;
    name: string;
}
ts

I will make an observable for the button. When the button is clicked, we will make a request for some data. When the request is complete, we will render the data to the DOM. If the request fails, we will log the error.

const getUsers = () => {
    return Observable.create((observer: Observer<JSON>) => {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(response => response.json())
            .then(data => {
                observer.next(data);
                observer.complete();
            })
            .catch(error => {
                observer.error(error);
            });
    })
};
ts

This is a dummy function that takes an array of users and renders them to the DOM.

const renderUsers = (users: User[]) => {
    const ul = document.querySelector('ul');
    users.forEach(user => {
        const li = document.createElement('li');
        li.innerText = user.name;
        ul.appendChild(li);
    });
}
ts

I will use fromEvent() as it is a function that takes an event and returns an Observable. flatMap() takes the response from the fetch and flattens it into a single stream of values. subscribe() takes the response from the fetch and passes it to the renderUsers() function.

Observable.fromEvent(button, 'click')
    .flatMap(() => getUsers())
    .subscribe((users: User[]) => {
        renderUsers(users);
    })
ts