SlideShare a Scribd company logo
1 of 34
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

Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observablesStefan Charsley
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...Katy Slemon
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to SwaggerKnoldus Inc.
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolvedtrxcllnt
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Knoldus Inc.
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3 ArezooKmn
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular ComponentsSquash Apps Pvt Ltd
 

What's hot (20)

JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Express JS
Express JSExpress JS
Express JS
 
NestJS
NestJSNestJS
NestJS
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Express js
Express jsExpress js
Express js
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 

Similar to Introduction to RxJS

Reactive programming and RxJS
Reactive programming and RxJSReactive programming and RxJS
Reactive programming and RxJSRavi Mone
 
From zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptFrom zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptMaurice De Beijer [MVP]
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixTracy Lee
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptViliam Elischer
 
From zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptFrom zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptMaurice De Beijer [MVP]
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentChui-Wen Chiu
 
GDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJSGDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJSPratik Majumdar
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaKros Huang
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Morris Singer
 
Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014hezamu
 
BASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive appBASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive appHanaStevanovic
 
Reactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary GrygleskiReactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary GrygleskiPolyglotMeetups
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkNikos Kalogridis
 

Similar to Introduction to RxJS (20)

Reactive programming and RxJS
Reactive programming and RxJSReactive programming and RxJS
Reactive programming and RxJS
 
From zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptFrom zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java script
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMix
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
From zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptFrom zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScript
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Intro to Rx Java
Intro to Rx JavaIntro to Rx Java
Intro to Rx Java
 
DZone_RC_RxJS
DZone_RC_RxJSDZone_RC_RxJS
DZone_RC_RxJS
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
GDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJSGDSC NITS Presents Kickstart into ReactJS
GDSC NITS Presents Kickstart into ReactJS
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014Functional UIs with Java 8 and Vaadin JavaOne2014
Functional UIs with Java 8 and Vaadin JavaOne2014
 
BASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive appBASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive app
 
Reactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary GrygleskiReactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary Grygleski
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI framework
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 

Recently uploaded (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 

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()