Reactive in Android and Beyond Rx

50
Reactive in Android & beyond Rx Fabio Tiriticco / @ticofab DAUG Meetup 23 August 2016

Transcript of Reactive in Android and Beyond Rx

Page 1: Reactive in Android and Beyond Rx

Reactive in Android & beyond Rx

Fabio Tiriticco / @ticofab

DAUG Meetup 23 August 2016

Page 2: Reactive in Android and Beyond Rx

A little info about myself

AndroidEngineerBackendArchitect

Page 3: Reactive in Android and Beyond Rx

The Reactive Amsterdam meetup

Reactive Amsterdam

• cross-technology• cross-domain

Page 4: Reactive in Android and Beyond Rx

“Reactive” in the vocabulary

Reactive (adjective):

Tending to act in response to an agent or influence

Page 5: Reactive in Android and Beyond Rx

Reactive Confusion

FunctionalReactiveProgramming

Reactiveinthecontextofthe“ReactiveManifesto”

OR

Page 6: Reactive in Android and Beyond Rx

Reactive Programming

Page 7: Reactive in Android and Beyond Rx

Why Functional?

Moresupportiveofreasoningaboutproblemsinconcurrentandparallelisedapplications.

• encouragesuseofpurefunctions-minimisesideeffects• encouragesimmutability-statedoesn’tgetpassedaround• higher-orderfunctions-reusabilityandcomposability

Page 8: Reactive in Android and Beyond Rx

Hello, RxJava!

Mobileengineeringishardandtherearehighexpectations.

RxJavaiscoolbecause

• itmakesitsupereasytoswitchbetweenthreads• letsusdealwithdataasastream• bringsussomedegreeoffunctionalprogramming

Page 9: Reactive in Android and Beyond Rx

Hello, RxJava!

RxJava

RxJs

RxClojure

RxSwift

• Asynchronousprogramming• Observablestreams

Opensourcelibrariesfor

Page 10: Reactive in Android and Beyond Rx

RxJava goes hand in hand with Java8’s Lambdas

new Func1<String, Integer>() { @Override public Integer call(String s) { return s.length(); }}

(String s) -> { return s.length();}

s -> s.length();

RetrolambapluginforAndroid<N

Page 11: Reactive in Android and Beyond Rx

RxJava: dealing with a stream of items

class Cat {...public String getName()public Color getColor()public Picture fetchPicture()...

}

Page 12: Reactive in Android and Beyond Rx

RxJava: dealing with a stream of items

Observable.from(myCats); cat -> Timber.d(cat.getName())

List<Cat> myCats;

Observable obs = obs.subscribe( );

Observable.from(myCats).subscribe(cat -> Timber.d(cat.getName()));

Page 13: Reactive in Android and Beyond Rx

RxJava: work on the stream

Observable.from(myCats)

.subscribe(color -> Timber.d(color));

map: function that takes T => outputs R

.map( )cat -> cat.getColor()

Page 14: Reactive in Android and Beyond Rx

RxJava: operators to manipulate the stream

Observable.from(myCats).distinct().delay(2, TimeUnit.SECONDS).filter(cat -> cat.getColor().isWhite()).map(cat -> cat.getName()).subscribe(name ->

Timber.d(“a unique, delayed white cat called ” + name));

Page 15: Reactive in Android and Beyond Rx

Observable.from(myCats).subscribe(

cat -> Timber.d(cat.getName()),error -> error.printStackTrace(),() -> Timber.d(“no more cats”)

);

RxJava: subscriber interface

Observable.from(myCats).subscribe(

onNext<T>, // next item TonError, // throwableonComplete // void

);

Page 16: Reactive in Android and Beyond Rx

Observable.from(myCats) .subscribe(cat -> Timber.d(“cat”));

RxJava: unsubscribe

Subscription subs =

subs.unsubscribe();

Page 17: Reactive in Android and Beyond Rx

RxJava: threading

Observable.from(myCats)

.map(cat -> cat.fetchPicture())

.map(picture -> Filter.applyFilter(picture))

.subscribe(filteredPicture -> display(filteredPicture)

);

.subscribeOn(Schedulers.newThread())

.observeOn(AndroidSchedulers.mainThread())

Page 18: Reactive in Android and Beyond Rx

RxJava: other ways of creating Observables

// emits on single item and completesObservable.just

// emits one item after a certain delayObservable.timer

// emits a series of integers at regular paceObservable.interval

.. plus many others, and you can create your own — BUT TRY NOT TO -

Page 19: Reactive in Android and Beyond Rx

RxJava: a few disadvantages

• debuggingismoredifficult• methodswithsideeffects• powerfulabstraction-lotofstuffunderthehood

Page 20: Reactive in Android and Beyond Rx

RxJava: demo with Retrofit & Meetup Streams

http://stream.meetup.com/2/rsvp

Meetup Streaming API

Page 21: Reactive in Android and Beyond Rx

RxJava: demo with Meetup Streams

Page 22: Reactive in Android and Beyond Rx

RxJava: demo with Retrofit & Meetup Streams

interface MeetupAPI { @GET("http://stream.meetup.com/2/rsvp") @Streaming Observable<ResponseBody> meetupStream();}

Page 23: Reactive in Android and Beyond Rx

RxJava: demo with RSVP Meetup Streams

meetupAPI.meetupStream()....flatMap(responseBody -> events(responseBody.source())).map(string -> gson.fromJson(string, RSVP.class))... .subscribe(rsvp -> ...);

map: T => RflatMap: T => Observable<R>

Page 24: Reactive in Android and Beyond Rx

RxJava: demo with Meetup Streams

Page 25: Reactive in Android and Beyond Rx

RxJava: demo with Meetup Streams

https://github.com/ticofab/android-meetup-streams

Page 26: Reactive in Android and Beyond Rx

2006 2016

Servers ~10 Theskyisthelimit.

Responsetime seconds milliseconds

Offlinemaintenance hours what?

Dataamount Gigabytes Petabytes

Machines Singlecore,littledistribution Mustworkacrossasyncboundaries(location,threads)

Kindofdata Request-response Streams(endless)

Reactive in the sense of the Reactive Manifesto

Page 27: Reactive in Android and Beyond Rx

Evolution of internet usage

Page 28: Reactive in Android and Beyond Rx

The Reactive traits

Areactivecomputersystemmust Trait

Reacttoitsusers Responsive

Reacttofailureandstayavailable Resilient

Reacttovaryingloadconditions Elastic

Itscomponentsmustreacttoinputs Message-driven

Page 29: Reactive in Android and Beyond Rx

Reactive traits: Responsive

• Ahumanwhovisitsawebsite• Aclientwhichmakesarequesttoaserver• Aconsumerwhichcontactsaprovider• ...

AReactivesystemrespondstoinputsandusagefromitsuser.

Page 30: Reactive in Android and Beyond Rx

Reactive traits: Elastic

• ScaleOUTandIN:usejusttherightamount• Elasticityreliesondistribution• Ensurereplicationincaseoffailure

Scaleondemandtoreacttovaryingload

Page 31: Reactive in Android and Beyond Rx

Reactive traits: Resilient

Itdoesn'tmatterhowgreatyourapplicationisifitdoesn'twork.

FAULTTOLERANCE RESILIENCEVS

Page 32: Reactive in Android and Beyond Rx

Reactive traits: Message Driven

ReactivesystemsdesignconcentratesonMessages.

Asynchronousmessagingenables:

• Separationbetweencomponents• Errorcontainment-avoidchainfailures• Domainmappingclosertoreality

Page 33: Reactive in Android and Beyond Rx

The Reactive Manifesto

Page 34: Reactive in Android and Beyond Rx

Reactive Patterns

DesignpatternstoachieveReactiveprinciples.

Toolkitsexisttoimplementthesepatterns.

Page 35: Reactive in Android and Beyond Rx

Reactive Pattern: Simple Component Pattern

“Onecomponentshoulddoonlyonethingbutdoitinfull.Theaimistomaximisecohesionandminimisecouplingbetweencomponents.”

Page 36: Reactive in Android and Beyond Rx

Reactive Pattern: Simple Component Pattern

Actor1

Actor3

Actor2

• containsstate• hasamailboxtoreceiveandsendmessages

• containsbehaviourlogic• hasasupervisor

ActormodelSupervisor

Page 37: Reactive in Android and Beyond Rx

Example: Synchronous DB access

Activity DBservice DB

List<Cat> cats = new ArrayList<Cat>();try {

cats = dbService.getAllCats();} catch (ExampleException e) {

// TODO}

Page 38: Reactive in Android and Beyond Rx

Example: DB access with callback

dbService.getAllCats(new OnCompleted() {@Overridepublic void onDataRetrieved(List<Cat> cats) {

// TODO}

});

Activity DBservice DB

Page 39: Reactive in Android and Beyond Rx

Example: Async Messaging with Actors

Activityactor DBActor DB

Page 40: Reactive in Android and Beyond Rx

Example: Async Messaging with Actors - messages

// message to ask for catspublic class GetCats {}

// message to send results backpublic class Results {

ArrayList<Cat> mCats;public Results(ArrayList<Cat> cats) {

mCats = cats;}

}

Page 41: Reactive in Android and Beyond Rx

Example: Async Messaging with Actors - behaviour

// db actor pseudocode@Overridepublic void onReceive(Message message) {

}

if (message is GetCats) {

}

// retrieve cats from databasec = contentResolver.query(...)...// send cats to the ActivityResults result = new Results(cats);activityAddress.tell(result)

Page 42: Reactive in Android and Beyond Rx

Reactive Patterns: Let it crash!

"Preferafullcomponentrestarttocomplexinternalfailurehandling".

• failureconditionsWILLoccur• theymightberareandhardtoreproduce• itismuchbettertostartcleanthantotrytorecover• …whichmightbeexpensiveanddifficult!

Page 43: Reactive in Android and Beyond Rx

Reactive Patterns: Let it crash!

Actorsupervisionexample

Actor1

Actor2

Supervisor

WhateverException!

X

FixorRestart

Page 44: Reactive in Android and Beyond Rx

Reactive Patterns: Let it crash!

• themachineonlyacceptsexactchange

Page 45: Reactive in Android and Beyond Rx

Reactive Patterns: Let it crash!

Scenario1:Theuserinsertswrongamountofcoins

X

Error

Page 46: Reactive in Android and Beyond Rx

Reactive Patterns: Let it crash!

Scenario2:Themachineisoutofcoffeebeans

Failure(!=error)

Page 47: Reactive in Android and Beyond Rx

Reactive Patterns: Let it crash!

Page 48: Reactive in Android and Beyond Rx

Recap

• TriedtoclarifytheReactiveConfusion• ExamplesofFRPinAndroid• ReactiveprinciplesfromtheReactiveManifesto• AcoupleofDesignPatternstoachievethem• (withaglimpseofpseudoimplementation)

Reactive Amsterdam

Page 49: Reactive in Android and Beyond Rx

Thanks!

@ticofab

All pictures belong to their respective authors

AMSTERDAM 11-12 MAY 2016

Page 50: Reactive in Android and Beyond Rx

Resources

https://github.com/ReactiveX/RxJava/wiki RxJavadocumentation&wiki

http://rxmarbles.com RxJavaoperatorsexplainedvisually

http://www.reactivemanifesto.org Thereactivemanifesto

https://www.youtube.com/watch?v=fNEZtx1VVAkhttps://www.youtube.com/watch?v=ryIAibBibQIhttps://www.youtube.com/watch?v=JvbUF33sKf8

TheReactiveRevealedseries:awesomewebinarsbythecreatorsoftheReactiveManifesto.

https://www.manning.com/books/reactive-design-patternshttps://www.youtube.com/watch?v=nSfXcSWq0ug Reactivedesignpatterns,bookandwebinar.