reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · rx...

26
Reactive programming: origins & ecosystem Jonas Chapuis, Ph.D.

Upload: others

Post on 21-May-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Reactiveprogramming:origins&ecosystem

JonasChapuis,Ph.D.

Page 2: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Timeline

“FunctionalReactiveAnimation”

(FranLibrary,Haskell)

1997 2009

Rx1.0for.NET,ErikMeijer&teamat

Microsoft

Elmlanguage

2012

RxforJava,Netflix

2013

Rxonallplatforms&manyotherlibraries

today

Reactivestreamsstandard

2015

Page 3: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Reactiveprogrammingecosystem

JVM

Flows API

Monix (scala)

Projectreactor

KafkaStreams

RxJava 2.0

www.reactive-streams.orgStandardizationgroup

.NET

Rx.NET4.0

PHP

hack

Web/JS

RxJS 5.0

dartstreams

Cycle.js

Page 4: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

ReactiveX (Rx)

› “Everydayattheoffice”functionalreactiveprogramming• Integratesinimperativelanguages• Strongsupportforerrorhandling&testing

› Platforms• C#• Java• JavaScript• Scala• C++• Python• Ruby• Swift• …

http://reactivex.io/

Page 5: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

OriginofFRP

› FunctionalReactiveAnimation (‘97),Conal Elliott&PaulHudak

› Domain-specificlanguage(DSL)fordescribinganimations› “Vectorized”descriptionofmovement– samplingisdoneatrenderingtime(e.g.60images/second)

Page 6: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Behaviors:continuousvaluesovertime

Source:Franlibrarytutorial

waggle = cos (pi * time)

wiggle = sin (pi * time)

patOrbitsCharlotte = stretch wiggle charlotte `over` moveXY wiggle waggle pat

orbitAndLater = orbit `over` later 1 orbitwhere

orbit = moveXY wiggle waggle jake

f(time) -> value

Page 7: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Evenin3D!

spiralTurn = turn3 zVector3 (pi*time) (unionGs (map ball [1 .. n])) where

n = 40ball i = withColorG color (

move3 motion ( stretch3 0.1 sphereLowRes ))

wheremotion = vector3Spherical 1.5 (10*phi) phi phi = pi * fromInt i / fromInt n color = colorHSL (2*phi) 0.5 0.5

Source:Franlibrarytutorial

Page 8: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Events:discretevaluesovertime

followMouseAndDelay u = follow `over` later 1 follow

where follow = move (mouseMotion u) jake

Source:Franlibrarytutorial

List[(time, value)]

Page 9: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Reactivebehavior:until

redBlue u = buttonMonitor u `over`

withColor c circlewhere c = red `until` click u -=> blue

redBlueCycle u = buttonMonitor u `over`withColor (cycle red blue u) circle

where cycle c1 c2 u = c1 `until` nextUser_ click u ==> cycle c2 c1

Source:Franlibrarytutorial

behaviorA until event -> behaviorB

Page 10: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

First-orderFRP(Elm)

› DSLforwebapps(compilestoJavaScript)• Purelyfunctional• DrivesthePrezi fancypresentationswebservice

› ConceptofSignal• Infinitesequencesofvaluesovertime(events)• Signalskeeptheirhistory• Novariablemutation,it’sallevents(eventsourcing)• Signalscomposetogetherwithtransformstodescribeprogramflow• Signalgraphsarestatic:“pipes”cannotbereroutedatruntime.Thismakesforadeterministicprogramwhichallowstime-travel andhot-swapping.

Page 11: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Inputs

Source:FRPflavorsbyElmcreatorEvanCzaplicki

Page 12: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Transformations

Source:FRPflavorsbyElmcreatorEvanCzaplicki

Page 13: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

State

Page 14: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Example:hot-swappingsupermario

› Supermario demo

Page 15: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

FunctionalReactiveProgramming(FRP)

› Explicitconsiderationoftime(latency)Traditionalprogramflow:noconsiderationoflatency

FRPprogram:allowswritingcodewhichaccountsforlatency

time(scheduler)

Page 16: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Interruptcodeafter5min…ohmy

TimeoutException!

final Runnable doSomeLengthyStuff = new Thread() {@Overridepublic void run() {/* Do stuff here. */

}};

final ExecutorService executor = Executors.newSingleThreadExecutor();final Future future = executor.submit(stuffToDo);executor.shutdown(); // This does not cancel the already-scheduled task.

try {future.get(5, TimeUnit.MINUTES);

}catch (InterruptedException ie) {/* Handle the interruption. Or ignore it. */

}catch (ExecutionException ee) {/* Handle the error. Or ignore it. */

}catch (TimeoutException te) {/* Handle the timeout. Or ignore it. */

}if (!executor.isTerminated())

executor.shutdownNow(); // If you want to stop the code that hasn't finished.

Page 17: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Ok,howaboutthis:

Observable.fromCallable(() -> doSomeLengthyStuff()).timeout(5, TimeUnit.MINUTES).retry(3).subscribe(

result => /*handle result*/,exception => /* definite failure after 3 attempts, handle here*/);

Page 18: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

FunctionalReactiveProgramming(FRP)

› Compositionthroughfunctionalprogramming

flatMap:

Page 19: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

FlavorsofFRP

› Representationoftime• Discrete(mostlibraries)• Continuous(academic)

› Composition• Fixed(Elm)• Dynamic(Rx)

› Drive• Push-based(Rx)• Pull-based(scala’s FS2,Ix)

Page 20: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Fouressentialeffects

singlevalue multiplevaluesPull(Synchronous/Interactive)

Object(orFailure) Iterable (Array|Set|Map)

Push(Asynchronous/Reactive)

Promise(aka.Future,Task) Observable(aka.Stream,Publisher)

FRP

Page 21: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Yin&Yang

Pull (Iterable) Push (Observable)

MoveNext() OnNext()

• Eventstreams• Asynchronous computations• Asynchronous queries• Asynchronous enumerations• …

• Inmemorycollections• Databasequeries• Generatedsequences• Messagequeues• …

Page 22: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Higher-orderFRP:asynchronousdataflow

› Dynamicgraphs,thankstoSignalsofSignals• Wecanswitchsignals,createnewsignals,etc.

› Switchingsignalsmeanswelosehot-swappingortime-travelling• Sincewecan’tpreventivelykeepallhistoryofsignalswehaven’tcreatedyet!

Page 23: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

High-orderFRP:flatmap

› Coreoperationrequired:flatmap()flatmap: Signal (Signal a) -> Signal a

Diagram:ReactiveProgramming withRxJava,T.Nurkiewicz &BenChrisensen,O’Reilly

Page 24: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

RxJS +React +Redux demo

› Timetravellingthroughredux“eventsourcing”› Cancellationsupport› Debouncing,timeout,etc.› Avoideventloopswithonedirectionalbinding&richactionsandepics

› Testingasynchronicity (cancellation,timeout,errors)

Page 25: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Summary

› Nowadaysstrongecosystem,paradigmofchoicetoprogramforthecloud

Page 26: Reactive programming: origins & ecosystemjonaschapuis.com/wp-content/uploads/2017/09/... · Rx for Java, Netflix 2013 Rx on all platforms & many other libraries today Reactive streams

Comingupnext

› Typescript:anintroduction› Declarativeandfunctionalprogramming:programwithoutloops› Synchronousandasynchronousprogramming:latency,callbacks,observerpattern,promises,async/await

› Functionalreactiveprogramming:observablesandobservers› Rxoperatorsandmarblediagrams› Generators,resourcehandling,hotandcoldobservables› Concurrencyandschedulers,virtualtimeandtesting› Errorhandling,resilience,scalabilityandbackpressure› Reactivearchitectures:react/redux,distributedsystems,microservices,actors