SlideShare a Scribd company logo
1 of 31
Download to read offline
Moving towards
Reactive Programming
LSPE MeetUp
March 14, 2015
Hello !!
I am Deepak Shevani
- Work at Flipkart for Supply Chain team
- Recently got interested in
@reactive @functional @programming
- Contact : shevanideepak@gmail.com
Agenda for talk
▧ Awareness, what’s up ??
▧ Reactive, what’s this ??
▧ Reactive Programming
▧ Functional Reactive Programming
▧ Demo(s)
Disclaimer : While I make every effort to tell
correct information, I am still a learner :)
Noob Alert !!
“Be aware of technology advancements.
Java 8 design is heavily influenced by core
principles of functional programming !!
Brian Goetz
#1 JAVA is functional
We should start thinking events as signals
emitted from some asynchronous data stream
Eric Meijer
#2 Streams everywhere
Think about this !!
Suppose, we have to design a
button with click counter that
tracks different clicks and
perform appropriate actions.
Say, we’ll print separate
messages for each click
observed.
Pure JS Implementation
var timer, timeout = 200; // timer reset in ms
button.addEventListener("dblclick", function (evt) {
timer = setTimeout(function () {
timer = null;
}, timeout);
});
button.addEventListener("click", function (evt) {
if (timer) {
console.log("triple");
label.textContent = "success!";
clearTimeout(timer);
timer = null;
}
});
1.
Reactive, what ??
Let’s understand - what reactive means ?
What reactive means ??
Merriam Webster
adjective re·ac·tive
rē-ˈak-tiv
Readily responsive to a
stimulus
Wikipedia
A reactive system is a system
that responds (reacts) to
external events.
Typically, computer systems
are reactive, when they react
to external as well as internal
events.
Reactive Manifesto !!
Excerpts from Manifesto
#Changing Needs
…. These changes are
happening because
modern application
requirements have
changed dramatically
in recent years.
#New Architectures
…. Today's demands
are simply not met by
yesterday’s software
architectures.
…. A new architecture
has evolved to let
developers build
applications to satisfy
these needs.
#Reactive Applications
…. We want systems
that are responsive,
resilient, elastic and
message Driven.
We call these Reactive
Systems.
Changing requirements
Few years ago Now
Server Nodes 10’s 1000’s
Response Times seconds milliseconds
Maintenance downtimes hours none
Data volume GBs TBs -> PBs
Traits of Reactive Applications
Event Driven
Traditionally, systems are composed of threads
which communicate with shared mutable state
Systems are better composed of loosely
coupled event handlers + asynchronous IO
Resilient
System should quickly recover from
failures (hardware, software, network)
How ? Loose coupling, thought out right
from beginning, handle exceptions, fbs
Scalable
Systems should be able to adjust itself
based on usage
- scale up : make use of parallelism
- scale out : multiple server nodes
Responsive (GOAL)
Application is ‘responsive’ if it provides
rich, real-time interaction with its users
even under load and in presence of
failures
Event-Driven
Handling events is not new.
Its often done using
callbacks.
Heard of - EventHandlers?
Problems :
- Shared mutable state
- Call-back hell
We do this already. No ??
Scalable
Distributed systems generally
allow scaling-out. What about
vertical scaling ? Is our code
easy to parallelize ?
Problems :
- Asynchronous programming
is hard, but we need this.
Is this revolutionary ??
or evolutionary ??
2.
Reactive Programming :)
Having understood what is reactive system
Let’s summarize our learnings
& start reactive programming
1. Never Block
- unless you really have to
- use non-blocking IO
- use lock-free concurrency
2. Go Async
- use asynchronous events/messages
- nothing to be shared (mutable state)
- design workflows with events flowing
- strive for loosely coupled message handlers
3. Go lazy
- efficiency != doing tasks faster
- avoid tasks that shouldn’t be done in the
first place.
- function composition and lazy evaluation
are pillars of reactive programming
Reactive programming is programming with
asynchronous data streams
Think - everything is a stream (not just clicks and hover events)
Anything can be stream - variables, user inputs, data structures
?
Functional Reactive Programming (FRP) is a
variant of Reactive Programming thats seeks
to be purely functional.
?
Functional => Lambdas, Closures, (Mostly) Pure, Composition
Reactive => Asynchronous, Events, Push based
Finally !! Tool set
Rx
The Reactive Extensions is a
library for composing
asynchronous event-based
programs. Developed by
Microsoft Open Technologies.
Bacon.js
A small functional reactive
programming library for
JavaScript. Turns your event
spaghetti using functional
programming paradigms.
RAC
Reactive Cocoa (RAC) is an
Objective-C framework
inspired by Functional
Reactive Programming.
Elm
A functional reactive
language for interactive
applications.
Play
Written in Scala and Java,
play makes iterative,
Reactive application
development very simple.
Akka
Akka is a tool kit and runtime
for building highly concurrent
distributed, and resilient
message-driven applications
on the JVM
4.
Demo Time
Show me some code
Just a moment !!
Streams
A stream is a
sequence of ongoing
events ordered in
time. Emits three
things
- value
- error
- completed
Observables
If you have heard of
Observer Pattern, this is
a logical extension
where we deal with
streams of data that
- signals end
- handles failures
- does lazy evaluation
- uses push instead of
pull interaction
Subscriber
Captures emitted
events synchronously
Defines separate
functions for
- emitted values
- handle errors
- completion
Demo 1 : Click Counter
In this demo, we will consider
click events arising from a
button, and performs actions
like
- track double clicks
- track multiple (2+) clicks
as double click events
- subscribe to events
Demo 1 - Code
var clickStream = Rx.Observable.fromEvent(button, 'click');
var multiClickStream =
clickStream
.buffer (
function() {
return clickStream.throttle(250);
})
.map (
function(list) {
return list.length;
})
.filter (
function(x) {
return x >= 2;
});
Demo 1 - Code
multiClickStream.subscribe (
function (numclicks) {
document.querySelector('h4').textContent = 'This was '+numclicks+'x click';
}
);
Rx.Observable.merge (singleClickStream, multiClickStream)
.throttle (5000)
.subscribe (
function (suggestion) {
document.querySelector('h4').textContent = 'Idle period for me ...';
}
);
Demo 2 : Rx-Java
In this demo, we will create a
reactive stock server
application using Rx Java
We will
- learn working with
streams
- learn handling errors
- see laziness live
- We will use Rx Java to
create streams out of
server responses and let
subscribers to
- subscribe
- unsubscribe
- filter etc
Demo 2 - Lazy Code
public static void main(String[] args) {
List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6);
System.out.println(
values.stream()
.filter(LazyStreamDemo::isGreaterThan3)
.filter(LazyStreamDemo::isEven)
.map(LazyStreamDemo::doubleIt)
.findFirst()
) ; } }
isGreaterThan3 - 3
isGreaterThan3 - 4
isEven - 4
doubleIt - 4
Thanks !!
You were a wonderful audience
Any questions?
You can find me at
@deepak_shevani
shevanideepak@gmail.com

More Related Content

Viewers also liked

Enterprise build tool gradle
Enterprise build tool gradleEnterprise build tool gradle
Enterprise build tool gradleDeepak Shevani
 
Javaone - Gradle: Harder, Better, Stronger, Faster
Javaone - Gradle: Harder, Better, Stronger, Faster Javaone - Gradle: Harder, Better, Stronger, Faster
Javaone - Gradle: Harder, Better, Stronger, Faster Andres Almiray
 
Terraforming organisations
Terraforming organisationsTerraforming organisations
Terraforming organisationsClaudio Perrone
 
Gradle - time for a new build
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new buildIgor Khotin
 
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Rajmahendra Hegde
 
Setting up an Investment Bank
Setting up an Investment BankSetting up an Investment Bank
Setting up an Investment Bankrizwan ansari
 

Viewers also liked (9)

Enterprise build tool gradle
Enterprise build tool gradleEnterprise build tool gradle
Enterprise build tool gradle
 
Javaone - Gradle: Harder, Better, Stronger, Faster
Javaone - Gradle: Harder, Better, Stronger, Faster Javaone - Gradle: Harder, Better, Stronger, Faster
Javaone - Gradle: Harder, Better, Stronger, Faster
 
Terraforming organisations
Terraforming organisationsTerraforming organisations
Terraforming organisations
 
Gradle - time for a new build
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new build
 
Gradle
GradleGradle
Gradle
 
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
 
Gradle by Example
Gradle by ExampleGradle by Example
Gradle by Example
 
Gradle
GradleGradle
Gradle
 
Setting up an Investment Bank
Setting up an Investment BankSetting up an Investment Bank
Setting up an Investment Bank
 

Similar to Moving towards Reactive Programming

The macro of microservices
The macro of microservicesThe macro of microservices
The macro of microservicesSoftware Guru
 
Functional Requirements Of System Requirements
Functional Requirements Of System RequirementsFunctional Requirements Of System Requirements
Functional Requirements Of System RequirementsLaura Arrigo
 
ReactiveCocoa - Functional Reactive Programming concepts in iOS
ReactiveCocoa - Functional Reactive Programming concepts in iOSReactiveCocoa - Functional Reactive Programming concepts in iOS
ReactiveCocoa - Functional Reactive Programming concepts in iOSAndrei Popa
 
Debugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programsDebugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programsPVS-Studio
 
Reactive programming with cycle.js
Reactive programming with cycle.jsReactive programming with cycle.js
Reactive programming with cycle.jsluca mezzalira
 
MODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxMODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxVeerannaKotagi1
 
Scaling Engineering with Docker
Scaling Engineering with DockerScaling Engineering with Docker
Scaling Engineering with DockerTom Leach
 
The Taming Of The Code
The Taming Of The CodeThe Taming Of The Code
The Taming Of The CodeAlan Stevens
 
Postmortem of a uwp xaml application development
Postmortem of a uwp xaml application developmentPostmortem of a uwp xaml application development
Postmortem of a uwp xaml application developmentDavid Catuhe
 
Simplified DevOps Bliss -with OpenAI API
Simplified DevOps Bliss -with OpenAI APISimplified DevOps Bliss -with OpenAI API
Simplified DevOps Bliss -with OpenAI APIVictorSzoltysek
 
Java performance tuning
Java performance tuningJava performance tuning
Java performance tuningJerry Kurian
 
Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Anna Shymchenko
 
Being Reactive with Spring
Being Reactive with SpringBeing Reactive with Spring
Being Reactive with SpringKris Galea
 
Build reactive systems on lambda
Build reactive systems on lambdaBuild reactive systems on lambda
Build reactive systems on lambdaYan Cui
 
Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016
Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016
Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016DevOpsDays Tel Aviv
 

Similar to Moving towards Reactive Programming (20)

Combine in iOS - Basics
Combine in iOS - BasicsCombine in iOS - Basics
Combine in iOS - Basics
 
The macro of microservices
The macro of microservicesThe macro of microservices
The macro of microservices
 
GMR PROJECT PPT
GMR PROJECT PPTGMR PROJECT PPT
GMR PROJECT PPT
 
Functional Requirements Of System Requirements
Functional Requirements Of System RequirementsFunctional Requirements Of System Requirements
Functional Requirements Of System Requirements
 
ReactiveCocoa - Functional Reactive Programming concepts in iOS
ReactiveCocoa - Functional Reactive Programming concepts in iOSReactiveCocoa - Functional Reactive Programming concepts in iOS
ReactiveCocoa - Functional Reactive Programming concepts in iOS
 
Rx Swift
Rx SwiftRx Swift
Rx Swift
 
Srgoc java
Srgoc javaSrgoc java
Srgoc java
 
Debugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programsDebugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programs
 
Reactive programming with cycle.js
Reactive programming with cycle.jsReactive programming with cycle.js
Reactive programming with cycle.js
 
MODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxMODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptx
 
Scaling Engineering with Docker
Scaling Engineering with DockerScaling Engineering with Docker
Scaling Engineering with Docker
 
The Taming Of The Code
The Taming Of The CodeThe Taming Of The Code
The Taming Of The Code
 
Postmortem of a uwp xaml application development
Postmortem of a uwp xaml application developmentPostmortem of a uwp xaml application development
Postmortem of a uwp xaml application development
 
Simplified DevOps Bliss -with OpenAI API
Simplified DevOps Bliss -with OpenAI APISimplified DevOps Bliss -with OpenAI API
Simplified DevOps Bliss -with OpenAI API
 
Java performance tuning
Java performance tuningJava performance tuning
Java performance tuning
 
WoMakersCode 2016 - Shit Happens
WoMakersCode 2016 -  Shit HappensWoMakersCode 2016 -  Shit Happens
WoMakersCode 2016 - Shit Happens
 
Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"Орхан Гасимов: "Reactive Applications in Java with Akka"
Орхан Гасимов: "Reactive Applications in Java with Akka"
 
Being Reactive with Spring
Being Reactive with SpringBeing Reactive with Spring
Being Reactive with Spring
 
Build reactive systems on lambda
Build reactive systems on lambdaBuild reactive systems on lambda
Build reactive systems on lambda
 
Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016
Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016
Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016
 

More from Deepak Shevani

Intro to Azure Machine Learning
Intro to Azure Machine LearningIntro to Azure Machine Learning
Intro to Azure Machine LearningDeepak Shevani
 
EmergingTrendsInComputingAndProgrammingLanguages
EmergingTrendsInComputingAndProgrammingLanguagesEmergingTrendsInComputingAndProgrammingLanguages
EmergingTrendsInComputingAndProgrammingLanguagesDeepak Shevani
 
Java 8-streams-and-parallelism
Java 8-streams-and-parallelismJava 8-streams-and-parallelism
Java 8-streams-and-parallelismDeepak Shevani
 
Deepak semantic web_iitd
Deepak semantic web_iitdDeepak semantic web_iitd
Deepak semantic web_iitdDeepak Shevani
 

More from Deepak Shevani (6)

GraphQL
GraphQLGraphQL
GraphQL
 
Intro to Azure Machine Learning
Intro to Azure Machine LearningIntro to Azure Machine Learning
Intro to Azure Machine Learning
 
EmergingTrendsInComputingAndProgrammingLanguages
EmergingTrendsInComputingAndProgrammingLanguagesEmergingTrendsInComputingAndProgrammingLanguages
EmergingTrendsInComputingAndProgrammingLanguages
 
Java 8-streams-and-parallelism
Java 8-streams-and-parallelismJava 8-streams-and-parallelism
Java 8-streams-and-parallelism
 
Deepak semantic web_iitd
Deepak semantic web_iitdDeepak semantic web_iitd
Deepak semantic web_iitd
 
Yahoo! Time Traveler
Yahoo! Time TravelerYahoo! Time Traveler
Yahoo! Time Traveler
 

Recently uploaded

Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsDILIPKUMARMONDAL6
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 

Recently uploaded (20)

young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teams
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 

Moving towards Reactive Programming

  • 2. Hello !! I am Deepak Shevani - Work at Flipkart for Supply Chain team - Recently got interested in @reactive @functional @programming - Contact : shevanideepak@gmail.com
  • 3. Agenda for talk ▧ Awareness, what’s up ?? ▧ Reactive, what’s this ?? ▧ Reactive Programming ▧ Functional Reactive Programming ▧ Demo(s) Disclaimer : While I make every effort to tell correct information, I am still a learner :) Noob Alert !!
  • 4. “Be aware of technology advancements.
  • 5. Java 8 design is heavily influenced by core principles of functional programming !! Brian Goetz #1 JAVA is functional
  • 6. We should start thinking events as signals emitted from some asynchronous data stream Eric Meijer #2 Streams everywhere
  • 7. Think about this !! Suppose, we have to design a button with click counter that tracks different clicks and perform appropriate actions. Say, we’ll print separate messages for each click observed.
  • 8. Pure JS Implementation var timer, timeout = 200; // timer reset in ms button.addEventListener("dblclick", function (evt) { timer = setTimeout(function () { timer = null; }, timeout); }); button.addEventListener("click", function (evt) { if (timer) { console.log("triple"); label.textContent = "success!"; clearTimeout(timer); timer = null; } });
  • 9. 1. Reactive, what ?? Let’s understand - what reactive means ?
  • 10. What reactive means ?? Merriam Webster adjective re·ac·tive rē-ˈak-tiv Readily responsive to a stimulus Wikipedia A reactive system is a system that responds (reacts) to external events. Typically, computer systems are reactive, when they react to external as well as internal events.
  • 12. Excerpts from Manifesto #Changing Needs …. These changes are happening because modern application requirements have changed dramatically in recent years. #New Architectures …. Today's demands are simply not met by yesterday’s software architectures. …. A new architecture has evolved to let developers build applications to satisfy these needs. #Reactive Applications …. We want systems that are responsive, resilient, elastic and message Driven. We call these Reactive Systems.
  • 13. Changing requirements Few years ago Now Server Nodes 10’s 1000’s Response Times seconds milliseconds Maintenance downtimes hours none Data volume GBs TBs -> PBs
  • 14. Traits of Reactive Applications Event Driven Traditionally, systems are composed of threads which communicate with shared mutable state Systems are better composed of loosely coupled event handlers + asynchronous IO Resilient System should quickly recover from failures (hardware, software, network) How ? Loose coupling, thought out right from beginning, handle exceptions, fbs Scalable Systems should be able to adjust itself based on usage - scale up : make use of parallelism - scale out : multiple server nodes Responsive (GOAL) Application is ‘responsive’ if it provides rich, real-time interaction with its users even under load and in presence of failures
  • 15. Event-Driven Handling events is not new. Its often done using callbacks. Heard of - EventHandlers? Problems : - Shared mutable state - Call-back hell We do this already. No ?? Scalable Distributed systems generally allow scaling-out. What about vertical scaling ? Is our code easy to parallelize ? Problems : - Asynchronous programming is hard, but we need this.
  • 16. Is this revolutionary ?? or evolutionary ??
  • 17. 2. Reactive Programming :) Having understood what is reactive system Let’s summarize our learnings & start reactive programming
  • 18. 1. Never Block - unless you really have to - use non-blocking IO - use lock-free concurrency
  • 19. 2. Go Async - use asynchronous events/messages - nothing to be shared (mutable state) - design workflows with events flowing - strive for loosely coupled message handlers
  • 20. 3. Go lazy - efficiency != doing tasks faster - avoid tasks that shouldn’t be done in the first place. - function composition and lazy evaluation are pillars of reactive programming
  • 21. Reactive programming is programming with asynchronous data streams Think - everything is a stream (not just clicks and hover events) Anything can be stream - variables, user inputs, data structures ?
  • 22. Functional Reactive Programming (FRP) is a variant of Reactive Programming thats seeks to be purely functional. ? Functional => Lambdas, Closures, (Mostly) Pure, Composition Reactive => Asynchronous, Events, Push based
  • 23. Finally !! Tool set Rx The Reactive Extensions is a library for composing asynchronous event-based programs. Developed by Microsoft Open Technologies. Bacon.js A small functional reactive programming library for JavaScript. Turns your event spaghetti using functional programming paradigms. RAC Reactive Cocoa (RAC) is an Objective-C framework inspired by Functional Reactive Programming. Elm A functional reactive language for interactive applications. Play Written in Scala and Java, play makes iterative, Reactive application development very simple. Akka Akka is a tool kit and runtime for building highly concurrent distributed, and resilient message-driven applications on the JVM
  • 24. 4. Demo Time Show me some code
  • 25. Just a moment !! Streams A stream is a sequence of ongoing events ordered in time. Emits three things - value - error - completed Observables If you have heard of Observer Pattern, this is a logical extension where we deal with streams of data that - signals end - handles failures - does lazy evaluation - uses push instead of pull interaction Subscriber Captures emitted events synchronously Defines separate functions for - emitted values - handle errors - completion
  • 26. Demo 1 : Click Counter In this demo, we will consider click events arising from a button, and performs actions like - track double clicks - track multiple (2+) clicks as double click events - subscribe to events
  • 27. Demo 1 - Code var clickStream = Rx.Observable.fromEvent(button, 'click'); var multiClickStream = clickStream .buffer ( function() { return clickStream.throttle(250); }) .map ( function(list) { return list.length; }) .filter ( function(x) { return x >= 2; });
  • 28. Demo 1 - Code multiClickStream.subscribe ( function (numclicks) { document.querySelector('h4').textContent = 'This was '+numclicks+'x click'; } ); Rx.Observable.merge (singleClickStream, multiClickStream) .throttle (5000) .subscribe ( function (suggestion) { document.querySelector('h4').textContent = 'Idle period for me ...'; } );
  • 29. Demo 2 : Rx-Java In this demo, we will create a reactive stock server application using Rx Java We will - learn working with streams - learn handling errors - see laziness live - We will use Rx Java to create streams out of server responses and let subscribers to - subscribe - unsubscribe - filter etc
  • 30. Demo 2 - Lazy Code public static void main(String[] args) { List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6); System.out.println( values.stream() .filter(LazyStreamDemo::isGreaterThan3) .filter(LazyStreamDemo::isEven) .map(LazyStreamDemo::doubleIt) .findFirst() ) ; } } isGreaterThan3 - 3 isGreaterThan3 - 4 isEven - 4 doubleIt - 4
  • 31. Thanks !! You were a wonderful audience Any questions? You can find me at @deepak_shevani shevanideepak@gmail.com