31
Moving towards Reactive Programming LSPE MeetUp March 14, 2015

Moving towards Reactive Programming

Embed Size (px)

Citation preview

Page 1: Moving towards Reactive Programming

Moving towardsReactive Programming

LSPE MeetUpMarch 14, 2015

Page 2: Moving towards Reactive Programming

Hello !!I am Deepak Shevani

- Work at Flipkart for Supply Chain team- Recently got interested in @reactive @functional @programming- Contact : [email protected]

Page 3: Moving towards Reactive Programming

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 !!

Page 4: Moving towards Reactive Programming

“Be aware of technology advancements.

Page 5: Moving towards Reactive Programming

Java 8 design is heavily influenced by core principles of functional programming !!

Brian Goetz

#1 JAVA is functional

Page 6: Moving towards Reactive Programming

We should start thinking events as signals emitted from some asynchronous data stream

Eric Meijer

#2 Streams everywhere

Page 7: Moving towards Reactive Programming

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.

Page 8: Moving towards Reactive Programming

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;

}

});

Page 9: Moving towards Reactive Programming

1.Reactive, what ??

Let’s understand - what reactive means ?

Page 10: Moving towards Reactive Programming

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.

Page 11: Moving towards Reactive Programming

Reactive Manifesto !!

Page 12: Moving towards Reactive Programming

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.

Page 13: Moving towards Reactive Programming

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

Page 14: Moving towards Reactive Programming

Traits of Reactive Applications

Event DrivenTraditionally, systems are composed of threads which communicate with shared mutable state

Systems are better composed of loosely coupled event handlers + asynchronous IO

ResilientSystem should quickly recover from failures (hardware, software, network)

How ? Loose coupling, thought out right from beginning, handle exceptions, fbs

ScalableSystems 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

Page 15: Moving towards Reactive Programming

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.

Page 16: Moving towards Reactive Programming

Is this revolutionary ??or evolutionary ??

Page 17: Moving towards Reactive Programming

2.Reactive Programming :)

Having understood what is reactive systemLet’s summarize our learnings& start reactive programming

Page 18: Moving towards Reactive Programming

1. Never Block- unless you really have to- use non-blocking IO- use lock-free concurrency

Page 19: Moving towards Reactive Programming

2. Go Async- use asynchronous events/messages- nothing to be shared (mutable state)- design workflows with events flowing- strive for loosely coupled message handlers

Page 20: Moving towards Reactive Programming

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

Page 21: Moving towards Reactive Programming

Reactive programming is programming withasynchronous data streams

Think - everything is a stream (not just clicks and hover events)

Anything can be stream - variables, user inputs, data structures

?

Page 22: Moving towards Reactive Programming

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

Page 23: Moving towards Reactive Programming

Finally !! Tool set

RxThe Reactive Extensions is a library for composing asynchronous event-based programs. Developed by Microsoft Open Technologies.

Bacon.jsA small functional reactive programming library for JavaScript. Turns your event spaghetti using functional programming paradigms.

RACReactive Cocoa (RAC) is an Objective-C framework inspired by Functional Reactive Programming.

ElmA functional reactive language for interactive applications.

PlayWritten in Scala and Java, play makes iterative, Reactive application development very simple.

AkkaAkka is a tool kit and runtime for building highly concurrent distributed, and resilient message-driven applications on the JVM

Page 24: Moving towards Reactive Programming

4.Demo Time

Show me some code

Page 25: Moving towards Reactive Programming

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

Page 26: Moving towards Reactive Programming

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

Page 27: Moving towards Reactive Programming

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;

});

Page 28: Moving towards Reactive Programming

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 ...';

}

);

Page 29: Moving towards Reactive Programming

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

Page 30: Moving towards Reactive Programming

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

Page 31: Moving towards Reactive Programming

Thanks !!You were a wonderful audience

Any questions?

You can find me at@deepak_shevani

[email protected]