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

Post on 21-May-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Reactiveprogramming:origins&ecosystem

JonasChapuis,Ph.D.

Timeline

“FunctionalReactiveAnimation”

(FranLibrary,Haskell)

1997 2009

Rx1.0for.NET,ErikMeijer&teamat

Microsoft

Elmlanguage

2012

RxforJava,Netflix

2013

Rxonallplatforms&manyotherlibraries

today

Reactivestreamsstandard

2015

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

ReactiveX (Rx)

› “Everydayattheoffice”functionalreactiveprogramming• Integratesinimperativelanguages• Strongsupportforerrorhandling&testing

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

http://reactivex.io/

OriginofFRP

› FunctionalReactiveAnimation (‘97),Conal Elliott&PaulHudak

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

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

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

Events:discretevaluesovertime

followMouseAndDelay u = follow `over` later 1 follow

where follow = move (mouseMotion u) jake

Source:Franlibrarytutorial

List[(time, value)]

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

First-orderFRP(Elm)

› DSLforwebapps(compilestoJavaScript)• Purelyfunctional• DrivesthePrezi fancypresentationswebservice

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

Inputs

Source:FRPflavorsbyElmcreatorEvanCzaplicki

Transformations

Source:FRPflavorsbyElmcreatorEvanCzaplicki

State

Example:hot-swappingsupermario

› Supermario demo

FunctionalReactiveProgramming(FRP)

› Explicitconsiderationoftime(latency)Traditionalprogramflow:noconsiderationoflatency

FRPprogram:allowswritingcodewhichaccountsforlatency

time(scheduler)

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.

Ok,howaboutthis:

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

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

FunctionalReactiveProgramming(FRP)

› Compositionthroughfunctionalprogramming

flatMap:

FlavorsofFRP

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

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

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

Fouressentialeffects

singlevalue multiplevaluesPull(Synchronous/Interactive)

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

Push(Asynchronous/Reactive)

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

FRP

Yin&Yang

Pull (Iterable) Push (Observable)

MoveNext() OnNext()

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

• Inmemorycollections• Databasequeries• Generatedsequences• Messagequeues• …

Higher-orderFRP:asynchronousdataflow

› Dynamicgraphs,thankstoSignalsofSignals• Wecanswitchsignals,createnewsignals,etc.

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

High-orderFRP:flatmap

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

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

RxJS +React +Redux demo

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

› Testingasynchronicity (cancellation,timeout,errors)

Summary

› Nowadaysstrongecosystem,paradigmofchoicetoprogramforthecloud

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

top related