Skip to main content
search

© 2021 Excellerate. All Rights Reserved

In this post, we will see common uses of the RxJS (Reactive Extensions for JavaScript) library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

It provides many operators that are functions that build on the observables foundation to enable sophisticated manipulation of collections. Operators take configuration options, and return a function that takes a source observable. Consequently, when executing this returned function, the operator observes the source observable emitted values, transforms them, and returns a new observable of those transformed values.

Now we will see some operators and their use with examples.

  1. from: From converts various other objects and data types into observables.
  2. groupBy: It groups the repeated object from the list
  3. mergeMap: mergeMap converts all repeated object to an array
  4. pipe: It’s a method on observables that is used for composing operators.
const data = [
{id: 1, Name: "-2" },
{id: 2, Name: "-2" },
{id: 1, Name: "-2" },
{id: 3, Name: "-2" },
{id: 4, Name: "-2" },
{id: 2, Name: "-2" },
{id: 3, Name: "-2" },
{id: 5, Name: "-1"}
]
const source = from(data)
const values = source.pipe(
groupBy(val => val.id),
mergeMap(group => group.pipe(toArray()))

here, mergeMap uses toArray() merge data into array.

Reduce
const source = of(1, 2, 3, 4);
const example = source.pipe(reduce((acc, val) => acc + val));
const subscribe = example.subscribe(val => console.log('Sum:', val));
//output: Sum: 10'

Reduce passes the result of this callback (acc) from one array element to the other.

Delay

Delay delay’s the emitted values by a specified time.

const message = merge(
example.pipe(mapTo('Hello')),
example.pipe(mapTo('World!'), delay(1000)),
example.pipe(mapTo('Goodbye'), delay(2000)),
example.pipe(mapTo('World!'), delay(3000))
);
// Output: 'Hello'...'World!'...'Goodbye'...'World!'
shareReplay

Two service calls and two responses are returned when the API is called twice.

const ob$ = this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1')
ob$.subscribe((data) => {
console.log(data)
})
ob$.subscribe((data) => {
console.log(data)
})

shareReplay avoids the two service calls and yet gets two responses.

const ob$ = this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1').pipe(shareReplay())
ob$.subscribe((data) => {
console.log(data)
})
ob$.subscribe((data) => {
console.log(data)
})

shareReplay reduces duplicate service calls. In upcoming blogs we’ll discuss more more rxjs operators.

About the author

Sushil Joshi

Sushil is a UI and UX developer at Synerzip. He has been developing interfaces for more than five years and has extensive knowledge of Bootstrap Framework, CSS3 and SCSS (CSS preprocessor). Sushil holds a Masters in Computer Applications from Pune University.

Leave a Reply