SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Reactive programming - Observable
Reactive programming - ObservableReactive programming - Observable
Reactive programming - ObservableDragos Ionita
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive ProgrammingTom Bulatewicz, PhD
 
Reactive programming
Reactive programmingReactive programming
Reactive programmingSUDIP GHOSH
 
Declarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive ProgrammingDeclarative Concurrency with Reactive Programming
Declarative Concurrency with Reactive ProgrammingFlorian Stefan
 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive ProgrammingAndres 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 microservicesYaroslav Tkachenko
 
Akka for big data developers
Akka for big data developersAkka for big data developers
Akka for big data developersTaras Fedorov
 
Spring batch showCase
Spring batch showCaseSpring batch showCase
Spring batch showCasetaher abdo
 
Building Reactive webapp with React/Flux
Building Reactive webapp with React/FluxBuilding Reactive webapp with React/Flux
Building Reactive webapp with React/FluxKeuller 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 CoroutinesLauren 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 queriesINRIA-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 2015Till Rohrmann
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - TalkMatthias 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
 
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 FeaturesRandolf Geist
 

Was ist angesagt? (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
 

Ähnlich wie Reactive programming and RxJS

Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSAbul Hasan
 
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]
 
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 RxJavaRick 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
 
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 2016Trayan 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 appsOtto Chrons
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence 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 applicationsJeff Durta
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simplerAlexander 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
 
State management in a GraphQL era
State management in a GraphQL eraState management in a GraphQL era
State management in a GraphQL erakristijanmkd
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJSMattia Occhiuto
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaKros Huang
 

Ähnlich wie 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
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 

Kürzlich hochgeladen (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 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