RxJS With Angular

Sinan Öztürk
7 min readJan 19, 2024

--

  • RxJS is a library for reactive programming using Observables.
  • Rxjs is stands for Reactive Extensions for JavaScript.

What is Reactive Programming

  • Reactive programming, as you can understand from the name the main idea is reacting to changes in our application without blocking the flow.
  • It is an approach to handle asynchronous data streams and events.
  • Reactive programming is particularly useful in situations where events or data changes can occur at any time, and the application needs to react to those changes.

RxJS in Angular

Angular, uses RxJS for handling asynchronous operations.

  • RxJS simplify the managing state. if you combine RxJS features with angular dependency injection system you can share the state application wide with singleton services. You can check this for more information.
  • With RxJS it is much easier to create reactivity. You can easly handle asynchronous events like, handling user input, making HTTP requests, and managing state changes.
  • You can deal with different types of asynchronous data streams with RxJS. it can be user input, event or HTTP responses.

Lets Start With Terminology

Observable

  • Observable is a collection of items over time, unlike an array it doesn’t retain items.
  • Think a newspaper, news are published every day. That’s what observables do. It emits over time.
  • Angular Uses Observables, here are the some of them;
    - Routing emits parameters via paramMap Observable
    - FormControl emits value via valueChanges Observable
    - Http client emits the response via Observable
  • In this case example we are making a request for orders. HttpClient returns an observable.
  • Run this code and check the network tab in browser. There will be no network request.
  • It’s because observable doesn’t do anything until a consumer subscribe to it. To invoke the observable and see the values, we need to subscribe it.

Subscription

  • Subscription is an object that represents the execution of an observable.
  • When you subscibe to an observable, it will return the subscripton object.
  • Subscription object has methods and properties that allow you to manage this connection.
  • You must unsubscribe from observable to avoid memory leaks when you are done with it.

Note: In general you must unsubscribe from observables. But in http request you dont have to because angular unsubscribes under the hood.

  • How to get returned values from observable?
    - You can use observers.

Observer

  • Observer is a consumer of values delivered by an Observable. Observers are simply a set of callbacks, 3 types of notifications delivered by the Observable.
    - next: The next item is emitted.
    - error: An error occured and no more items are emitted.
    - complete: No more items are emitted.
  • To use the observer, give it to the subscribe method of observable.

Uncommon way

  • Mostly we just give the next function as an argument to the subscribe method.
  • You can catch the error and completions via pipepable operators.

Operators

  • Operators are the essential pieces that allow complex asynchronous code to be easily writed like a declarative.
  • There are two kind of operators.
  • Pipepable operators;
    - Pipeable Operators
    transforms the each emitted item.
  • A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. It is a pure operation: the previous Observable stays unmodified.
  • Common Pipeable RxJS Operators
    - tap:
    Taps into the stream without changing it.
    - map:
    Basic transformation.
    - catchError:
    Catches errors.
    - finalize: Runs when the observable completes.
  • In the above image we dont have an observer, i wanted to show you that it is not mandatory.

Creation Operators

  • creation operators are for creating a new observable. for Example;

Subjects

  • A Subject is like an Observable, but can multicast to many Observers.
  • You can think this as a singer in concert. the singer(subject) is deliver the song to many people(observers).
  • We have subscribed the productSubject from 2 different component. When the new values emitted from productSubject, Our observers in the components will be notified.

There are 4 variants of subjects:

  • Subject — There is no initial value when declaring a new subject.
  • AsyncSubject — Emits latest value to observers and only when the execution completes.
  • BehaviorSubject — Requires an initial value and emits its current value (last emitted item) to new subscribers.
  • ReplaySubject — Emits specified number of last emitted values (a replay) to new subscribers.

High Order Mapping Operators

  • High order mapping operators also known as flatten operators.
  • What is first order operator;
  • First order operator is transforms each emitted value and emits the result, it’s actually a simple mapping operation.
  • High order mapping is transforms each emitted value to an Observable.
  • in the above code, we are getting the id from selectionChange$ observable and give it to the service.getTodo() method which returns Observable<Todo>.
  • We are expecting the type of todo$ is Observable<Todo>.
  • i have subscribed to the outer observable(todo$) via async pipe. But it still doesnt work, Why?
  • Because we didnt subscribed to the inner observable.
  • You might want to solve this with problem via subscribing to the inner observable, but it is not a good way. It will be hard to unsubscribe and there will be memory leaks.
  • Before showing the solution, lets see these terms;
    - Inner Observable;
    - Outer Observable;

See The Problems Again:

  • Problem 1: We didnt subscribe to the inner observable.
  • Problem 2: Response type is not the type that we want. The response type should be Observable<Todo>.
  • So we need to flatten the type, and subscribe to the inner observable.
  • High order mapping operators are going to solve our 2 problem here, as shown.
  • Flatten the response type.
  • Automatically subscribed to inner observable.
  • As you can see, switchMap subscribed to the inner observable (this.service.getTodo(id!)), and flatted the response type.

High Order Mapping Operators

  • Map each value from a outer observable to new inner observable.
  • Automatically subscribes and unsubscribes.
  • Emit the resulting values to the output observable.

Usefull Higher-Order Mapping Operators

1-) SwitchMap

  • Imagine you are making a request in every selection. you have picked the first selection and suddenly want to see the second selection. if the first network request is not done yet switchMap will cancel that request and make the new request for second selection.

2-) MergeMap
When to use mergeMap;

  • Making a network request in parallel, like race.
  • When order of response is doesn’t matter.
  • Imagine you need bunch of todos, and you want to get them.
  • As you can see, there is no order. If you want to order them, you can do something like this.

3-) ConcatMap

When to use concatMap;

  • Wait for the prior observable to start next one.
  • Make a network requests in sequence, one by one
  • When the order is important.
  • in this case i have used toArray(), thats why it waits all of the requests. if you dont use toArray() you can get them one by one sequentially.

Combination Operators

  • Combination operators allows you to combine, join informations from multiple observables. ordering, time etc.
  • So to work with multiple streams, we can use combination operators.

Combine Latest

  • When any observable emits a value, emit the last emitted value from each observable.
  • combineLatest will not emit an initial value until each observable emits at least one value.
  • Imagine you have multiple observable that rely on each other, combine latest is a good choice.

Merge

  • Emits the one value when any of the Observables emit

forkJoin

  • When all observables complete, emit the last emitted value from each.
  • If an inner observable does not complete forkJoin will never emit a value!

There are more in RxJS, thats all from me. Please share your ideas, tricks or advices with me

--

--