SlideShare a Scribd company logo
Introduction to RxJS
Abul Hasan
Senior Front-End Developer
SELISE
What we discuss?
➔ What is Rx & RxJS?
➔ What is Observable?
➔ What is Subscribing?
➔ Observable vs Promise
➔ Subscribe method shorthand notation
➔ What are the Observable creation function
➔ Why RxJS?
➔ Operators
◆ fromEvent, from, ajax, interval
◆ Subject, BehaviorSubject
◆ Filter, map, debounceTime, distinctUntilChanged
◆ forkJoin, mergeMap, switchMap
What is Rx?
➔ Rx is an API for asynchronous programming with observable streams.
➔ ReactiveX is a combination of the best ideas from the Observer pattern, the
Iterator pattern, and functional programming.
What is RxJS?
➔ JavaScript library
➔ Composing asynchronous and callback-based code in a functional, reactive
style using Observables.
➔ Many APIs such as HttpClient produce and consume RxJS Observables
What is Observable?
➔ A unique Object similar to promise
➔ It can help manage async code
➔ Stream of data
➔ Lazy Push collections of multiple values.
➔ It’s not part of JS language, so we need a popular Observable library called
RxJS
Observable Creation Example
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
setTimeout(() => {
observer.next('Hello from a Observable!');
}, 2000);
});
What is Subscribing?
➔ An Observable instance begins publishing values only when someone
subscribes to it.
➔ So you need to subscribe by calling the subscribe() method of the instance
Observables, Observers and Subscriptions
The Stream
Observable vs Promise
Observable Promise
Computation does not start until
subscription so that they can be run
whenever you need the result
Execute immediately on creation
Provide multiple values over time Provide only one
Pull vs Push
➔ Pull and Push are two different protocols that describe how a data Producer
can communicate with a data Consumer.
➔ Every JavaScript Function is a Pull system.
Subscribe method shorthand notation
The subscribe() method can accept callback function definitions in line, for next, error, and complete
handlers is known as shorthand notation.
observable.subscribe({
next(x){console.log('Observer got a next value: ' + x)},
error(err){console.error('Observer got an error: ' + err)},
complete(){console.log('Observer got a complete notification')}
});
What are the Observable creation function
RxJS creating observables from things such as Promises, Ajax requests, Timers,
Events.
1. from ( Promise )
2. ajax ( Ajax )
3. interval ( Timers )
4. fromEvent ( Events )
1. Create an observable from a promise
import { from } from 'rxjs'; // from function
const data = from(fetch('/api/endpoint')); //Created from Promise
data.subscribe({
next(response) { console.log(response); },
error(err) { console.error('Error: ' + err); },
complete() { console.log('Completed'); }
});
2. Create an observable that creates an AJAX request
import { ajax } from 'rxjs/ajax'; // ajax function
const apiData = ajax('/api/data'); // Created from AJAX request
// Subscribe to create the request
apiData.subscribe(res => console.log(res.status, res.response));
3. Create an observable from a counter
import { interval } from 'rxjs'; // interval function
const secondsCounter = interval(1000); // Created from Counter value
secondsCounter.subscribe(n => console.log(`Counter value: ${n}`));
4. Create an observable from an event
import { fromEvent } from 'rxjs';
const el = document.getElementById('custom-element');
const mouseMoves = fromEvent(el, 'mousemove');
const subscription = mouseMoves.subscribe((e: MouseEvent) => {
console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);
});
Why RxJS?
let button=document.querySelector('button');
button.addEventListener('click',(event)=>console.log(event));
import { fromEvent } from 'rxjs';
fromEvent(button, 'click')
.subscribe(
(event)=>console.log(event)
);
Here we see that it’s looks like funnel where event pass from top to
bottom
Vanilla JS
var count=0;
var rate=1000;
var lastClick=Date.now() - rate;
var button=document.querySelector('button');
button.addEventListener('click',(event)=>{
if(Date.now()-lastClick>=rate){
console.log(`Clicked ${++count} times`);
lastClick=Date.now();
}
});
With RxJS
fromEvent(button, 'click')
.throttleTime(1000)
.subscribe(
(event)=>console.log(event)
);
➔ Observable offers many many useful operators.
➔ Operators use for transform data
With RxJS
fromEvent(button, 'click')
.pipe(
throttleTime(1000),
map((data)=>{return data.clientX}))
.subscribe(
(event)=>console.log(event)
);
➔ We have funnel like approach
➔ Use operators for transform data which is more powerful
➔ Handle async code
Operators
➔ Operators are functions.
➔ RxJS is mostly useful for its operators
➔ It allow complex asynchronous code to be easily composed in a declarative
manner.
Two kind of operators:
1. Pipeable Operators
2. Creation Operators
Operators Continue..
Subject
Subject Continue ...
➔ An RxJS Subject is a special type of Observable
➔ It allows values to be multicasted to many Observers
➔ ...only upcoming values
import { Subject } from 'rxjs';
const subject = new Subject<number>();
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
subject.next(1);
BehaviorSubject
➔ Special type of Subject
➔ It has initial value
➔ It will emit the last value for new observer
➔ ...one previous value and upcoming values
filter operator
import { fromEvent } from 'rxjs';
import { filter } from 'rxjs/operators';
const clicks = fromEvent(document, 'click');
const clicksOnDivs = clicks.pipe(filter(ev => ev.target.tagName === 'DIV'));
clicksOnDivs.subscribe(x => console.log(x));
debounceTime
fromEvent(input, ‘input’)
.pipe(
debounceTime(2000)
)
.subscribe((event)=>{
console.log(event.target.value);
})
debounceTime & distinctUntilChanged
fromEvent(input, ‘input’)
.pipe(
debounceTime(2000),
distinctUntilChanged()
)
.subscribe((event)=>{
console.log(event.target.value);
})
debounceTime & distinctUntilChanged
fromEvent(input, ‘input’)
.pipe(
map(event=>event.target.value),
debounceTime(2000),
distinctUntilChanged()
)
.subscribe((value)=>{
console.log(value);
})
mergeMap()
obs1.pipe(mergeMap(
event1=>{
return obs2.pipe(map(
event2=> event1+event2
))
})
)
➔ Allow connect observable
➔ Emit value after inner observable complete
switchMap()
obs1.pipe(switchMap(
event1=>{
return obs2.pipe(map(
event2=> event1+event2
))
})
)
➔ Allow connect observable
➔ Emit value after inner observable complete
➔ Cancel previous request if new request come
➔ Useful if we handle http request
forkJoin()
➔ When all observables complete, emit the last emitted value from each.
➔ Why use forkJoin?
forkJoin(
// as of RxJS 6.5+ we can use a dictionary of sources
{
google: ajax.getJSON('https://api.github.com/users/google'),
microsoft: ajax.getJSON('https://api.github.com/users/microsoft'),
users: ajax.getJSON('https://api.github.com/users')
}
)
// { google: object, microsoft: object, users: array }
.subscribe(console.log);
Other operators
➔ take(1) ( Emit provided number of values before completing. )
➔ takeUntil() ( until provided observable emits. )
➔ takeWhile() ( until provided expression is false. )
➔ first() ( Emit the first value )
➔ scan()
➔ reduce()

More Related Content

What's hot (20)

PDF
Angular and The Case for RxJS
Sandi Barr
 
PDF
Angular Observables & RxJS Introduction
Rahat Khanna a.k.a mAppMechanic
 
PPTX
Rxjs ppt
Christoffer Noring
 
PDF
Angular 2 observables
Geoffrey Filippi
 
PPTX
Top 10 RxJs Operators in Angular
Jalpesh Vadgama
 
PDF
Angular & RXJS: examples and use cases
Fabio Biondi
 
PDF
RxJS Evolved
trxcllnt
 
PPTX
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
PDF
RxJS - The Basics & The Future
Tracy Lee
 
PPTX
Introduction to es6
NexThoughts Technologies
 
PPT
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
PPTX
Angular modules in depth
Christoffer Noring
 
PDF
The New JavaScript: ES6
Rob Eisenberg
 
PDF
Svelte JS introduction
Mikhail Kuznetcov
 
PDF
ES6 presentation
ritika1
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PDF
Présentation Angular 2
Cynapsys It Hotspot
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PPTX
Angular 9
Raja Vishnu
 
PDF
Workshop 21: React Router
Visual Engineering
 
Angular and The Case for RxJS
Sandi Barr
 
Angular Observables & RxJS Introduction
Rahat Khanna a.k.a mAppMechanic
 
Angular 2 observables
Geoffrey Filippi
 
Top 10 RxJs Operators in Angular
Jalpesh Vadgama
 
Angular & RXJS: examples and use cases
Fabio Biondi
 
RxJS Evolved
trxcllnt
 
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
RxJS - The Basics & The Future
Tracy Lee
 
Introduction to es6
NexThoughts Technologies
 
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
Angular modules in depth
Christoffer Noring
 
The New JavaScript: ES6
Rob Eisenberg
 
Svelte JS introduction
Mikhail Kuznetcov
 
ES6 presentation
ritika1
 
TypeScript Introduction
Dmitry Sheiko
 
Présentation Angular 2
Cynapsys It Hotspot
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular 9
Raja Vishnu
 
Workshop 21: React Router
Visual Engineering
 

Similar to Introduction to RxJS (20)

PPTX
RxJS In-Depth - AngularConnect 2015
Ben Lesh
 
PPTX
Rx – reactive extensions
Voislav Mishevski
 
PDF
Rxjs kyivjs 2015
Alexander Mostovenko
 
PDF
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
PDF
My Gentle Introduction to RxJS
Mattia Occhiuto
 
PPTX
Functional Reactive Programming (FRP): Working with RxJS
Oswald Campesato
 
PPTX
Rxjs swetugg
Christoffer Noring
 
PDF
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
GeeksLab Odessa
 
PDF
rx.js make async programming simpler
Alexander Mostovenko
 
PDF
Reactive x
Gabriel Araujo
 
PPTX
Rxjs marble-testing
Christoffer Noring
 
PPTX
Angular2 rxjs
Christoffer Noring
 
PPTX
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
PDF
RxJS101 - What you need to know to get started with RxJS tomorrow
Viliam Elischer
 
PPTX
Rxjs ngvikings
Christoffer Noring
 
PPTX
From zero to hero with the reactive extensions for java script
Maurice De Beijer [MVP]
 
PPTX
From zero to hero with the reactive extensions for JavaScript
Maurice De Beijer [MVP]
 
PPTX
Promises, promises, and then observables
Stefan Charsley
 
PPTX
Workshop introduction-to-rxjs
KristinaBistrickiene1
 
PDF
Reactive programming and RxJS
Ravi Mone
 
RxJS In-Depth - AngularConnect 2015
Ben Lesh
 
Rx – reactive extensions
Voislav Mishevski
 
Rxjs kyivjs 2015
Alexander Mostovenko
 
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
My Gentle Introduction to RxJS
Mattia Occhiuto
 
Functional Reactive Programming (FRP): Working with RxJS
Oswald Campesato
 
Rxjs swetugg
Christoffer Noring
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
GeeksLab Odessa
 
rx.js make async programming simpler
Alexander Mostovenko
 
Reactive x
Gabriel Araujo
 
Rxjs marble-testing
Christoffer Noring
 
Angular2 rxjs
Christoffer Noring
 
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
RxJS101 - What you need to know to get started with RxJS tomorrow
Viliam Elischer
 
Rxjs ngvikings
Christoffer Noring
 
From zero to hero with the reactive extensions for java script
Maurice De Beijer [MVP]
 
From zero to hero with the reactive extensions for JavaScript
Maurice De Beijer [MVP]
 
Promises, promises, and then observables
Stefan Charsley
 
Workshop introduction-to-rxjs
KristinaBistrickiene1
 
Reactive programming and RxJS
Ravi Mone
 
Ad

Recently uploaded (20)

PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Ad

Introduction to RxJS

  • 1. Introduction to RxJS Abul Hasan Senior Front-End Developer SELISE
  • 2. What we discuss? ➔ What is Rx & RxJS? ➔ What is Observable? ➔ What is Subscribing? ➔ Observable vs Promise ➔ Subscribe method shorthand notation ➔ What are the Observable creation function ➔ Why RxJS? ➔ Operators ◆ fromEvent, from, ajax, interval ◆ Subject, BehaviorSubject ◆ Filter, map, debounceTime, distinctUntilChanged ◆ forkJoin, mergeMap, switchMap
  • 3. What is Rx? ➔ Rx is an API for asynchronous programming with observable streams. ➔ ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming.
  • 4. What is RxJS? ➔ JavaScript library ➔ Composing asynchronous and callback-based code in a functional, reactive style using Observables. ➔ Many APIs such as HttpClient produce and consume RxJS Observables
  • 5. What is Observable? ➔ A unique Object similar to promise ➔ It can help manage async code ➔ Stream of data ➔ Lazy Push collections of multiple values. ➔ It’s not part of JS language, so we need a popular Observable library called RxJS
  • 6. Observable Creation Example import { Observable } from 'rxjs'; const observable = new Observable(observer => { setTimeout(() => { observer.next('Hello from a Observable!'); }, 2000); });
  • 7. What is Subscribing? ➔ An Observable instance begins publishing values only when someone subscribes to it. ➔ So you need to subscribe by calling the subscribe() method of the instance
  • 10. Observable vs Promise Observable Promise Computation does not start until subscription so that they can be run whenever you need the result Execute immediately on creation Provide multiple values over time Provide only one
  • 11. Pull vs Push ➔ Pull and Push are two different protocols that describe how a data Producer can communicate with a data Consumer. ➔ Every JavaScript Function is a Pull system.
  • 12. Subscribe method shorthand notation The subscribe() method can accept callback function definitions in line, for next, error, and complete handlers is known as shorthand notation. observable.subscribe({ next(x){console.log('Observer got a next value: ' + x)}, error(err){console.error('Observer got an error: ' + err)}, complete(){console.log('Observer got a complete notification')} });
  • 13. What are the Observable creation function RxJS creating observables from things such as Promises, Ajax requests, Timers, Events. 1. from ( Promise ) 2. ajax ( Ajax ) 3. interval ( Timers ) 4. fromEvent ( Events )
  • 14. 1. Create an observable from a promise import { from } from 'rxjs'; // from function const data = from(fetch('/api/endpoint')); //Created from Promise data.subscribe({ next(response) { console.log(response); }, error(err) { console.error('Error: ' + err); }, complete() { console.log('Completed'); } });
  • 15. 2. Create an observable that creates an AJAX request import { ajax } from 'rxjs/ajax'; // ajax function const apiData = ajax('/api/data'); // Created from AJAX request // Subscribe to create the request apiData.subscribe(res => console.log(res.status, res.response));
  • 16. 3. Create an observable from a counter import { interval } from 'rxjs'; // interval function const secondsCounter = interval(1000); // Created from Counter value secondsCounter.subscribe(n => console.log(`Counter value: ${n}`));
  • 17. 4. Create an observable from an event import { fromEvent } from 'rxjs'; const el = document.getElementById('custom-element'); const mouseMoves = fromEvent(el, 'mousemove'); const subscription = mouseMoves.subscribe((e: MouseEvent) => { console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`); });
  • 18. Why RxJS? let button=document.querySelector('button'); button.addEventListener('click',(event)=>console.log(event)); import { fromEvent } from 'rxjs'; fromEvent(button, 'click') .subscribe( (event)=>console.log(event) ); Here we see that it’s looks like funnel where event pass from top to bottom
  • 19. Vanilla JS var count=0; var rate=1000; var lastClick=Date.now() - rate; var button=document.querySelector('button'); button.addEventListener('click',(event)=>{ if(Date.now()-lastClick>=rate){ console.log(`Clicked ${++count} times`); lastClick=Date.now(); } });
  • 20. With RxJS fromEvent(button, 'click') .throttleTime(1000) .subscribe( (event)=>console.log(event) ); ➔ Observable offers many many useful operators. ➔ Operators use for transform data
  • 21. With RxJS fromEvent(button, 'click') .pipe( throttleTime(1000), map((data)=>{return data.clientX})) .subscribe( (event)=>console.log(event) ); ➔ We have funnel like approach ➔ Use operators for transform data which is more powerful ➔ Handle async code
  • 22. Operators ➔ Operators are functions. ➔ RxJS is mostly useful for its operators ➔ It allow complex asynchronous code to be easily composed in a declarative manner. Two kind of operators: 1. Pipeable Operators 2. Creation Operators
  • 25. Subject Continue ... ➔ An RxJS Subject is a special type of Observable ➔ It allows values to be multicasted to many Observers ➔ ...only upcoming values import { Subject } from 'rxjs'; const subject = new Subject<number>(); subject.subscribe({ next: (v) => console.log(`observerA: ${v}`) }); subject.subscribe({ next: (v) => console.log(`observerB: ${v}`) }); subject.next(1);
  • 26. BehaviorSubject ➔ Special type of Subject ➔ It has initial value ➔ It will emit the last value for new observer ➔ ...one previous value and upcoming values
  • 27. filter operator import { fromEvent } from 'rxjs'; import { filter } from 'rxjs/operators'; const clicks = fromEvent(document, 'click'); const clicksOnDivs = clicks.pipe(filter(ev => ev.target.tagName === 'DIV')); clicksOnDivs.subscribe(x => console.log(x));
  • 29. debounceTime & distinctUntilChanged fromEvent(input, ‘input’) .pipe( debounceTime(2000), distinctUntilChanged() ) .subscribe((event)=>{ console.log(event.target.value); })
  • 30. debounceTime & distinctUntilChanged fromEvent(input, ‘input’) .pipe( map(event=>event.target.value), debounceTime(2000), distinctUntilChanged() ) .subscribe((value)=>{ console.log(value); })
  • 31. mergeMap() obs1.pipe(mergeMap( event1=>{ return obs2.pipe(map( event2=> event1+event2 )) }) ) ➔ Allow connect observable ➔ Emit value after inner observable complete
  • 32. switchMap() obs1.pipe(switchMap( event1=>{ return obs2.pipe(map( event2=> event1+event2 )) }) ) ➔ Allow connect observable ➔ Emit value after inner observable complete ➔ Cancel previous request if new request come ➔ Useful if we handle http request
  • 33. forkJoin() ➔ When all observables complete, emit the last emitted value from each. ➔ Why use forkJoin? forkJoin( // as of RxJS 6.5+ we can use a dictionary of sources { google: ajax.getJSON('https://api.github.com/users/google'), microsoft: ajax.getJSON('https://api.github.com/users/microsoft'), users: ajax.getJSON('https://api.github.com/users') } ) // { google: object, microsoft: object, users: array } .subscribe(console.log);
  • 34. Other operators ➔ take(1) ( Emit provided number of values before completing. ) ➔ takeUntil() ( until provided observable emits. ) ➔ takeWhile() ( until provided expression is false. ) ➔ first() ( Emit the first value ) ➔ scan() ➔ reduce()