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

Moving towards Reactive Programming

  • 1.
  • 2.
    Hello !! I amDeepak 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 oftechnology advancements.
  • 5.
    Java 8 designis heavily influenced by core principles of functional programming !! Brian Goetz #1 JAVA is functional
  • 6.
    We should startthinking 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 vartimer, 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’sunderstand - 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.
  • 11.
  • 12.
    Excerpts from Manifesto #ChangingNeeds …. 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 yearsago Now Server Nodes 10’s 1000’s Response Times seconds milliseconds Maintenance downtimes hours none Data volume GBs TBs -> PBs
  • 14.
    Traits of ReactiveApplications 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 isnot 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 :) Havingunderstood 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 isprogramming 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 !! Toolset 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.
  • 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 werea wonderful audience Any questions? You can find me at @deepak_shevani shevanideepak@gmail.com