Introduction to Reactive Programming with Rxjs

Rebai Ahmed
6 min readDec 15, 2020

--

Introduction :

Hello guys, this is another blog for my “2020 blogging series challenge”, the topic this time is “Introduction to Reactive programming” I will present The Reactive programming concept , after we will discover the Rxjs library and some operators .

happy learning :)

What is Reactive Programming

“Reactive Programming is a declarative programming paradigm concerned with data streams and the propagation of change.”

Reactive programming is a programming paradigm that deals with asynchronous data streams (sequences of events) and the specific propagation of change, which means it implements modifications to the execution environment (context) in a certain order.

So when you will use Reactive programming , the stream it will be the main object used in your application

ReactiveX :

So to discover more the RX programming, you can visit ReactiveX,An API for asynchronous programming with observable streams

It provides some documentation and list the libraries libraries to implement Reactive programming with different dev languages like :

  • Java: RxJava
  • JavaScript: RxJS
  • Go: RxGo

Reactive Programming with Rxjs :

For our blog, we will practice RX with Rxjs one of the hottest libraries in web development today

What is Rxjs:

Reactive Extension for Javascript. It is a javascript library that uses observables to work with reactive programming that deals with asynchronous data calls, callbacks and event-based programs

  • RxJS allows you to create reactive programs with JavaScript to better serve your users.
  • RxJS is a library used to create asynchronous programs using observable sequences.
  • RxJS is one of the key libraries each modern JavaScript developer should have in his kit
  • It is a functional and powerful tool integrated into a wide range of frameworks
  • RxJS makes it easy for JavaScript developers to write asynchronous code using composable Observables instead of callbacks and Promises.

Why use RxJS?

  • Large and responsive community: One of the largest benefits of this library is its diversified and large community. Thanks to having such a responsive community, RxJS grows even stronger and more popular. Participants of the community help each other to handle the problems and questions on StackOverflow and Gitter.
  • Error-handling strategies become complicated when you begin nesting try/catch blocks within each callback. RxJS provides an error-handling approach from a functional perspective.
  • RxJS provides an ideal and easy mechanism to cancel events cleanly after some predetermined amount of time. Implementing your cancellation mechanism can be very challenging and error-prone even with the help of third-party libraries.
  • Flexible to Use
  • RxJS can easily be used with other Javascript libraries and frameworks such as Angular, ReactJS, Vue.js, Nodejs, etc. It is supported by JavaScript and also with TypeScript.
  • Provides good optimization and memory leaks protection

Rxjs Installation :

Now you can install rxjs using the below command :

npm install — -save-dev rxjs

You can then import the symbols you want to use from the rxjs package or a sub-package such as rxjs/operators:

import { Observable, Subscriber } from ‘rxjs’;
import { tap, map, filter } from ‘rxjs/operators’;

Rxjs Operators :

There are a lot of operators provided by Rxjs that covered many features and needs in our applications:

  • Map :

Map is a pretty simple operator. It takes a projection function and applies it to each value that comes from the source observable.

const namesObseravble = of('Ahmed', 'Rebai');namesObseravble.pipe(map((name) => `${name} is awesome !`)).subscribe((result) => console.log(`${result}`));
  • Pipe :

“Combining Multiple Operators”

RxJS provides two versions of the pipe() function: A standalone function and a method on the Observable interface.
You can use the pipe() function/method to combine multiple Operators.

For example: “RxJS data pipeline”:

const dataPipeline = arrayDataObservable$.pipe(
tap(val => console.log(‘Value passing through the stream: ‘ + val)),
filter(val => val > 2),
map(val => val * 2)
)
  • SwitchMap :

With switchMap() we only care about the latest and greatest, we don’t care about the past,one of the most use cases of swicthMap is the search

Example : “When you press a key and then you get suggestions for things that you want to write .

Every new input triggers a new HTTP request for that search term!”

With switchMap for each new search input, a new HTTP request will be done, and live the previous will be canceled

Example implementation :

searchBook() {
this.bookId.valueChanges.pipe(
switchMap(id => {
console.log(id);
return this.bookService.getBook(id);
})
).subscribe(res => this.book = res);
}
  • forkJoin:

this is very similar to Promise. all() and One common use case for this is if you wish to issue multiple requests on page load,

I will explain it in the code example :

I need to make two HTTP API calls

‘’’ In our example, we capture the character and characterHomeworld Observable in variables. Observables are lazy, so they won’t execute until someone subscribes. When we pass them into forkJoin the forkJoin the operator will subscribe and run each Observable, gathering up each value emitted and finally emitting a single array value containing all the completed HTTP requests.””

export class AppComponent {
loadedCharacter: {};
constructor(private http: HttpClient) {}

ngOnInit() {
let character = this.http.get('https://swapi.dev/api/people/1/');
let characterHomeworld = this.http.get('http://swapi.dev/api/planets/1/');

forkJoin([character, characterHomeworld]).subscribe(results => {
// results[0] is our character
// results[1] is our character homeworld
results[0].homeworld = results[1];
this.loadedCharacter = results[0];
});
}
}

Subject :

“A Subject is a special type of Observable that allows values to be multicasted to many Observers”

A Subject is a special type of Observable that observers can also subscribe to it to receive published values but with one difference: The values are multicasted to many Observers.

const mySubject = new Rx.Subject();

mySubject.next(1);

const subscription1 = mySubject.subscribe(x => {
console.log('From subscription 1:', x);
});

mySubject.next(2);

const subscription2 = mySubject.subscribe(x => {
console.log('From subscription 2:', x);
});

mySubject.next(3);

subscription1.unsubscribe();

mySubject.next(4);
  • pluck() +distinctUntilChanged():

distinctUntilChanged():Only emit when the current value is different than the last.

pluck(): Pluck simply picks one of the nested properties of each emitted value

var input = document.querySelector('input');
var observable = Rx.Observable.fromEvent(input, 'input');
observable
.pluck('target', 'value')
.debounceTime(500)
.distinctUntilChanged()
.subscribe({
next: function(value) {
console.log(value);
}
});

Conclusion :

For Conclusion, I just tried to share my experience trying to learn rxjs and practice its cool operators and the use cases of them, and tips for you guys if you want to learn something practice it and try to implement it in production in your project that you are working for, don’t fear

Resources :

--

--

Rebai Ahmed
Rebai Ahmed

No responses yet