SlideShare a Scribd company logo
Reactive Programming And RxJS
- Ravi Mone
Agenda
❏ What and Why Reactive Programming (The Reactive Way)
❏ Reactive Programming V/S Functional Programming
❏ What is RxJS (Reactive Extensions for JS)
❏ Why RxJS? What about Promises?
❏ Is it like a kinda lodash library ?
❏ What is Observables?
❏ Operators Agony
❏ Other Rx*'s
❏ Demo and Examples
❏ Resources and References
2
What and Why Reactive Programming
(The Reactive Way)
Let’s start by looking at a problem.
This program needs to retrieve data from different sources with the click of a button, and it has the
following requirements:
● It must unify data from two different locations that use different JSON structures.
● The final result should NOT contain any duplicates.
● To avoid requesting data too many times, the user should NOT be able to click the button more
than once per second.
3
Why Reactive Programming? Cont.
OK. NOW THINKING GOES IN Imperative WAY
1. write a function to call http calls (include a ajax library, for this) and return the response.
2. From the previous response apply some filters to remove duplications (again you may write a
function called `removeDuplicates`)
3. The other point I will leave it to you
which may include some interval, disable property on dom ... (again you may write a function called
`domChanges`)
4
Why Reactive Programming? Cont.
OK, NOW let's think in Reactive WAY:
Using RxJS, we would write something like this:
5
var button = document.getElementById('retrieveDataBtn');
var source1 = Rx.DOM.getJSON('/resource1').pluck('name');
var source2 = Rx.DOM.getJSON('/resource2').pluck('props',
'name');
function getResults(amount) {
return source1.merge(source2)
.pluck('names')
.flatMap(function(array) {
return Rx.Observable.from(array);
})
.distinct()
.take(amount);
}
Why Reactive Programming? Cont.
6
var clicks = Rx.Observable.fromEvent(button, 'click');
clicks.debounce(1000)
.flatMap(getResults(5))
.subscribe(
function(value) { console.log('Received value', value); },
function(err) { console.error(err); },
function() { console.log('All values retrieved!'); }
);
Why Reactive Programming? Cont.
Another Example :
Logs only the first 10 mouse clicks on the right side of the screen (quite a random goal).
we would write something like this:
(NOTE : YOU MESSED THE GLOBAL SCOPE)
7
var clicks = 0;
document.addEventListener('click', function registerClicks(e) {
if (clicks < 10) {
if (e.clientX > window.innerWidth / 2) {
console.log(e.clientX, e.clientY);
clicks += 1;
}
} else {
document.removeEventListener('click', registerClicks);
}
});
Why Reactive Programming? Cont.
Using RxJS, we would write something like this:
https://codepen.io/anon/pen/veqgQL
Another example:
DRAG & DROP, https://codepen.io/joshblack/pen/zGZZjX?editors=1010 explanation
8
Rx.Observable.fromEvent(document, 'click')
.filter(function(c) {
return c.clientX > window.innerWidth / 2;
})
.take(10)
.subscribe(function(c) {
console.log(c.clientX, c.clientY)
})
Reactive VS Functional Programming
In functional programming, you manipulate functions just as easily as you manipulate other data values
like integers and strings, we call this functions being a first class citizen. The concept behind functional
programming is that each time you call a function with the same parameters, it returns the same result. In
order to accomplish this, functional programming languages must not hold any kind of state. The
advantage of this is that it makes code easier to test, more predictable, and therefore, in theory, more
reliable.
Reactive Programming
Reactive programming is programming with asynchronous data streams. For example, your twitter feed
would be a data stream, your click events, user inputs, caches, data structures. You listen to that stream
and 'react' accordingly. So, reactive programming involves programming with time flow and
computational events
9
Reactive V/S Functional Programming Cont.
source :
https://www.quora.com/What-is-difference-between-Functional-Reactive-Programming-Functional-Pr
ogramming-and-Reactive-Programming
Understanding :
reactive programming is functional programming, but takes streaming to a higher level, you'll deal with a
bunch of events and every time something happens, you'll be notified and you'll have a stream, instead of
a concrete object every time.
for example:
Promise.resolve({a: true}) will give you an object {a: true}
while Observable.fromArray([1, 2, 3]).subscribe((e) => {console.log(e)}) will give you 1, 2, 3
10
Why RxJS? What about Promises?
RxJS is a library for reactive programming using observables, to make it easier to compose asynchronous
or callback-based code
Promises are good for solving asynchronous operations such as querying a service with an
XMLHttpRequest, where the expected behavior is one value and then completion. The Reactive
Extensions for JavaScript unifies both the world of Promises, callbacks as well as evented data such as
DOM Input, Web Workers, Web Sockets. Once we have unified these concepts, this enables rich
composition.
11
Why RxJS? What about Promises? Cont.
observable for Promises
You are probably comfortable with promises, then you can adapt to Observables easily
Observables are part of ES6 features, where it deals with async code likewise of promise, but has little
more powers than promises
12
promise.then(
successCallBackFn,
errorCallBackFn);
observable.subscribe(
nextCallBackFn,
errorCallBackFn,
completeCallBackFn
)
Is it like a kinda Lodash?
Of course RxJS is a library, same as lodash, but RxJS deals more with events, async calls like streams,
whereas lodash is more of functional programming where the data gets transformed in each function,
and RxJS is Reactive Programming (HAHA, you have much terminologies yet to come), which takes
streaming to a higher level, you'll deal with a bunch of events and every time something happens.
13
What is Observables?
In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or
sequence of items the Observable emits. This pattern provides concurrent operations because it does
not need to block while waiting for the Observable to emit objects, but instead it creates a sentry(a
soldier stationed to keep guard or to control access to a place.) in the form of an observer that stands
ready to react appropriately at whatever future time the Observable does so.
14
Operators Agony
1. Use the operator guide at http://reactivex.io/rxjs
2. Remember you don't have to Rx everything
3. Take the operators you know to whatever point you can and do the rest imperatively
15
Other Rx*’s
16
EXAMPLES
https://codepen.io/anon/pen/RLzVge
https://codepen.io/joshblack/pen/zGZZjX?editors=1010
https://gist.github.com/ravi-tj/47e14fa262700d62d5bdbee4b6fcf18e
17
Resources and References
rxjs thinking reactively
RxJS Observables Crash Course
https://www.youtube.com/watch?v=Tux1nhBPl_w
https://www.quora.com/What-is-functional-programming
18
Questions ?
Thanks
- Happy Coding

More Related Content

What's hot

Reactive programming - Observable
Reactive programming - ObservableReactive programming - Observable
Reactive programming - Observable
Dragos Ionita
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive Programming
Tom Bulatewicz, PhD
 
Project Reactor By Example
Project Reactor By ExampleProject Reactor By Example
Project Reactor By Example
Denny Abraham Cheriyan
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
SUDIP GHOSH
 
Declarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive ProgrammingDeclarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive Programming
Florian Stefan
 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive Programming
Andres Almiray
 
Why actor-based systems are the best for microservices
Why actor-based systems are the best for microservicesWhy actor-based systems are the best for microservices
Why actor-based systems are the best for microservices
Yaroslav Tkachenko
 
Akka for big data developers
Akka for big data developersAkka for big data developers
Akka for big data developers
Taras Fedorov
 
Spring batch showCase
Spring batch showCaseSpring batch showCase
Spring batch showCase
taher abdo
 
Building Reactive webapp with React/Flux
Building Reactive webapp with React/FluxBuilding Reactive webapp with React/Flux
Building Reactive webapp with React/Flux
Keuller Magalhães
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Lauren Yew
 
Prometheus Introduction (InfraCoders Vienna)
Prometheus Introduction (InfraCoders Vienna)Prometheus Introduction (InfraCoders Vienna)
Prometheus Introduction (InfraCoders Vienna)
Oliver Moser
 
Conjunctive queries
Conjunctive queriesConjunctive queries
Conjunctive queries
INRIA-OAK
 
Computing recommendations at extreme scale with Apache Flink @Buzzwords 2015
Computing recommendations at extreme scale with Apache Flink @Buzzwords 2015Computing recommendations at extreme scale with Apache Flink @Buzzwords 2015
Computing recommendations at extreme scale with Apache Flink @Buzzwords 2015
Till Rohrmann
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
Matthias Noback
 
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
Flink Forward
 
Scopes in mule
Scopes in muleScopes in mule
Scopes in mule
Ramakrishna kapa
 
Mini-Training: Let's have a rest
Mini-Training: Let's have a restMini-Training: Let's have a rest
Mini-Training: Let's have a rest
Betclic Everest Group Tech Team
 
Flink Forward Berlin 2017: Maciek Próchniak - TouK Nussknacker - creating Fli...
Flink Forward Berlin 2017: Maciek Próchniak - TouK Nussknacker - creating Fli...Flink Forward Berlin 2017: Maciek Próchniak - TouK Nussknacker - creating Fli...
Flink Forward Berlin 2017: Maciek Próchniak - TouK Nussknacker - creating Fli...
Flink Forward
 
Oracle 12c Parallel Execution New Features
Oracle 12c Parallel Execution New FeaturesOracle 12c Parallel Execution New Features
Oracle 12c Parallel Execution New Features
Randolf Geist
 

What's hot (20)

Reactive programming - Observable
Reactive programming - ObservableReactive programming - Observable
Reactive programming - Observable
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive Programming
 
Project Reactor By Example
Project Reactor By ExampleProject Reactor By Example
Project Reactor By Example
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Declarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive ProgrammingDeclarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive Programming
 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive Programming
 
Why actor-based systems are the best for microservices
Why actor-based systems are the best for microservicesWhy actor-based systems are the best for microservices
Why actor-based systems are the best for microservices
 
Akka for big data developers
Akka for big data developersAkka for big data developers
Akka for big data developers
 
Spring batch showCase
Spring batch showCaseSpring batch showCase
Spring batch showCase
 
Building Reactive webapp with React/Flux
Building Reactive webapp with React/FluxBuilding Reactive webapp with React/Flux
Building Reactive webapp with React/Flux
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
 
Prometheus Introduction (InfraCoders Vienna)
Prometheus Introduction (InfraCoders Vienna)Prometheus Introduction (InfraCoders Vienna)
Prometheus Introduction (InfraCoders Vienna)
 
Conjunctive queries
Conjunctive queriesConjunctive queries
Conjunctive queries
 
Computing recommendations at extreme scale with Apache Flink @Buzzwords 2015
Computing recommendations at extreme scale with Apache Flink @Buzzwords 2015Computing recommendations at extreme scale with Apache Flink @Buzzwords 2015
Computing recommendations at extreme scale with Apache Flink @Buzzwords 2015
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
 
Scopes in mule
Scopes in muleScopes in mule
Scopes in mule
 
Mini-Training: Let's have a rest
Mini-Training: Let's have a restMini-Training: Let's have a rest
Mini-Training: Let's have a rest
 
Flink Forward Berlin 2017: Maciek Próchniak - TouK Nussknacker - creating Fli...
Flink Forward Berlin 2017: Maciek Próchniak - TouK Nussknacker - creating Fli...Flink Forward Berlin 2017: Maciek Próchniak - TouK Nussknacker - creating Fli...
Flink Forward Berlin 2017: Maciek Próchniak - TouK Nussknacker - creating Fli...
 
Oracle 12c Parallel Execution New Features
Oracle 12c Parallel Execution New FeaturesOracle 12c Parallel Execution New Features
Oracle 12c Parallel Execution New Features
 

Similar to Reactive programming and RxJS

DZone_RC_RxJS
DZone_RC_RxJSDZone_RC_RxJS
DZone_RC_RxJS
Luis Atencio
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Abul Hasan
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
Christoffer Noring
 
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
Maurice De Beijer [MVP]
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
Jalpesh Vadgama
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PROIDEA
 
User Interface
User InterfaceUser Interface
User Interface
Nikunj Pansuriya
 
Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016
Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016
Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016
Trayan Iliev
 
Scala.js for large and complex frontend apps
Scala.js for large and complex frontend appsScala.js for large and complex frontend apps
Scala.js for large and complex frontend apps
Otto Chrons
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
Laurence Svekis ✔
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
Alexander Mostovenko
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
GeeksLab Odessa
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
State management in a GraphQL era
State management in a GraphQL eraState management in a GraphQL era
State management in a GraphQL era
kristijanmkd
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Brainhub
 
The Road To Redux
The Road To ReduxThe Road To Redux
The Road To Redux
Jeffrey Sanchez
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
Mattia Occhiuto
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
Kros Huang
 

Similar to Reactive programming and RxJS (20)

DZone_RC_RxJS
DZone_RC_RxJSDZone_RC_RxJS
DZone_RC_RxJS
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
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
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
User Interface
User InterfaceUser Interface
User Interface
 
Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016
Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016
Reactive Java Robotics and IoT - IPT Presentation @ Voxxed Days 2016
 
Scala.js for large and complex frontend apps
Scala.js for large and complex frontend appsScala.js for large and complex frontend apps
Scala.js for large and complex frontend apps
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
State management in a GraphQL era
State management in a GraphQL eraState management in a GraphQL era
State management in a GraphQL era
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
The Road To Redux
The Road To ReduxThe Road To Redux
The Road To Redux
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 

Recently uploaded

UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 

Recently uploaded (20)

UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 

Reactive programming and RxJS

  • 1. Reactive Programming And RxJS - Ravi Mone
  • 2. Agenda ❏ What and Why Reactive Programming (The Reactive Way) ❏ Reactive Programming V/S Functional Programming ❏ What is RxJS (Reactive Extensions for JS) ❏ Why RxJS? What about Promises? ❏ Is it like a kinda lodash library ? ❏ What is Observables? ❏ Operators Agony ❏ Other Rx*'s ❏ Demo and Examples ❏ Resources and References 2
  • 3. What and Why Reactive Programming (The Reactive Way) Let’s start by looking at a problem. This program needs to retrieve data from different sources with the click of a button, and it has the following requirements: ● It must unify data from two different locations that use different JSON structures. ● The final result should NOT contain any duplicates. ● To avoid requesting data too many times, the user should NOT be able to click the button more than once per second. 3
  • 4. Why Reactive Programming? Cont. OK. NOW THINKING GOES IN Imperative WAY 1. write a function to call http calls (include a ajax library, for this) and return the response. 2. From the previous response apply some filters to remove duplications (again you may write a function called `removeDuplicates`) 3. The other point I will leave it to you which may include some interval, disable property on dom ... (again you may write a function called `domChanges`) 4
  • 5. Why Reactive Programming? Cont. OK, NOW let's think in Reactive WAY: Using RxJS, we would write something like this: 5 var button = document.getElementById('retrieveDataBtn'); var source1 = Rx.DOM.getJSON('/resource1').pluck('name'); var source2 = Rx.DOM.getJSON('/resource2').pluck('props', 'name'); function getResults(amount) { return source1.merge(source2) .pluck('names') .flatMap(function(array) { return Rx.Observable.from(array); }) .distinct() .take(amount); }
  • 6. Why Reactive Programming? Cont. 6 var clicks = Rx.Observable.fromEvent(button, 'click'); clicks.debounce(1000) .flatMap(getResults(5)) .subscribe( function(value) { console.log('Received value', value); }, function(err) { console.error(err); }, function() { console.log('All values retrieved!'); } );
  • 7. Why Reactive Programming? Cont. Another Example : Logs only the first 10 mouse clicks on the right side of the screen (quite a random goal). we would write something like this: (NOTE : YOU MESSED THE GLOBAL SCOPE) 7 var clicks = 0; document.addEventListener('click', function registerClicks(e) { if (clicks < 10) { if (e.clientX > window.innerWidth / 2) { console.log(e.clientX, e.clientY); clicks += 1; } } else { document.removeEventListener('click', registerClicks); } });
  • 8. Why Reactive Programming? Cont. Using RxJS, we would write something like this: https://codepen.io/anon/pen/veqgQL Another example: DRAG & DROP, https://codepen.io/joshblack/pen/zGZZjX?editors=1010 explanation 8 Rx.Observable.fromEvent(document, 'click') .filter(function(c) { return c.clientX > window.innerWidth / 2; }) .take(10) .subscribe(function(c) { console.log(c.clientX, c.clientY) })
  • 9. Reactive VS Functional Programming In functional programming, you manipulate functions just as easily as you manipulate other data values like integers and strings, we call this functions being a first class citizen. The concept behind functional programming is that each time you call a function with the same parameters, it returns the same result. In order to accomplish this, functional programming languages must not hold any kind of state. The advantage of this is that it makes code easier to test, more predictable, and therefore, in theory, more reliable. Reactive Programming Reactive programming is programming with asynchronous data streams. For example, your twitter feed would be a data stream, your click events, user inputs, caches, data structures. You listen to that stream and 'react' accordingly. So, reactive programming involves programming with time flow and computational events 9
  • 10. Reactive V/S Functional Programming Cont. source : https://www.quora.com/What-is-difference-between-Functional-Reactive-Programming-Functional-Pr ogramming-and-Reactive-Programming Understanding : reactive programming is functional programming, but takes streaming to a higher level, you'll deal with a bunch of events and every time something happens, you'll be notified and you'll have a stream, instead of a concrete object every time. for example: Promise.resolve({a: true}) will give you an object {a: true} while Observable.fromArray([1, 2, 3]).subscribe((e) => {console.log(e)}) will give you 1, 2, 3 10
  • 11. Why RxJS? What about Promises? RxJS is a library for reactive programming using observables, to make it easier to compose asynchronous or callback-based code Promises are good for solving asynchronous operations such as querying a service with an XMLHttpRequest, where the expected behavior is one value and then completion. The Reactive Extensions for JavaScript unifies both the world of Promises, callbacks as well as evented data such as DOM Input, Web Workers, Web Sockets. Once we have unified these concepts, this enables rich composition. 11
  • 12. Why RxJS? What about Promises? Cont. observable for Promises You are probably comfortable with promises, then you can adapt to Observables easily Observables are part of ES6 features, where it deals with async code likewise of promise, but has little more powers than promises 12 promise.then( successCallBackFn, errorCallBackFn); observable.subscribe( nextCallBackFn, errorCallBackFn, completeCallBackFn )
  • 13. Is it like a kinda Lodash? Of course RxJS is a library, same as lodash, but RxJS deals more with events, async calls like streams, whereas lodash is more of functional programming where the data gets transformed in each function, and RxJS is Reactive Programming (HAHA, you have much terminologies yet to come), which takes streaming to a higher level, you'll deal with a bunch of events and every time something happens. 13
  • 14. What is Observables? In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits. This pattern provides concurrent operations because it does not need to block while waiting for the Observable to emit objects, but instead it creates a sentry(a soldier stationed to keep guard or to control access to a place.) in the form of an observer that stands ready to react appropriately at whatever future time the Observable does so. 14
  • 15. Operators Agony 1. Use the operator guide at http://reactivex.io/rxjs 2. Remember you don't have to Rx everything 3. Take the operators you know to whatever point you can and do the rest imperatively 15
  • 18. Resources and References rxjs thinking reactively RxJS Observables Crash Course https://www.youtube.com/watch?v=Tux1nhBPl_w https://www.quora.com/What-is-functional-programming 18