reactive android: rxjava and beyond

54
Reactive Android: RxJava & beyond Fabio Tiriticco / @ticofab AMSTERDAM 11-12 MAY 2016

Upload: fabio-tiriticco

Post on 16-Jan-2017

186 views

Category:

Technology


4 download

TRANSCRIPT

Reactive Android: RxJava & beyond

Fabio Tiriticco / @ticofab

AMSTERDAM 11-12 MAY 2016

A little info about myself

AndroidEngineerScalaEngineer

The Reactive Amsterdam meetup

Reactive Amsterdam

Because nobody knows what Reactive means

To explore the concept in all of its forms.

“Reactive” in the vocabulary

Reactive (adjective):

Tending to act in response to an agent or influence

Reactive Confusion

“IwasthinkingofusingNode.js,butmaybeIcanbuilditwithReactive.”

“ThanksforrunningameetupaboutReact.js”

Reactive Confusion

• Theconceptof“Reactive”hascommonbasisbutslightlydifferentmeaningsineachdomain

• MostofusthinkthatReactive==React.js

Twomainobservations:

Reactive in (Android) frontend VS backend

ANDROID

UsingRxJava

WHATDOPEOPLETHINKTHAT“BEINGREACTIVE”MEANS?

BACKEND

?

Hello, RxJava!

• Asynchronousprogramming• Observablestreams

Opensourcelibrariesfor

Hello, RxJava!

Mobileengineeringishardandtherearehighexpectations.

RxJavaiscoolbecause

• itmakesitsupereasytoswitchbetweenthreads• letsusdealwithdataasastream• bringsussomedegreeoffunctionalprogramming.

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

RxJava: dealing with a stream of items

class Cat {...public Collar getCollar() {…}public Picture fetchPicture() {…}...

}

RxJava: dealing with a stream of items

Observable.from(myCats);(cat -> Log.d(TAG, “got cat”));

List<Cat> myCats;

Observable obs = obs.subscribe

RxJava: dealing with a stream of items

Observable.from(myCats).subscribe(cat -> Log.d(TAG, “got cat”));

List<Cat> myCats;

RxJava: work on the stream

Observable.from(myCats).map(cat -> cat.getCollar()).subscribe(collar -> Log.d(TAG, “got collar”));

map: T -> R(this map: Cat -> Collar)

RxJava: operators to manipulate the stream

Observable.from(myCats).distinct().delay(2, TimeUnit.SECONDS).filter(cat -> cat.isWhite()).subscribe(cat -> Log.d(TAG, “got white cat”));

Observable.from(myCats).subscribe(

cat -> Log.d(TAG, “cat”),error -> error.printStackTrace(),() -> Log.d(TAG, “done”)

);

RxJava: subscriber interface

Observable<T>.from(myCats).subscribe(

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

);

Observable.from(myCats) .subscribe(cat -> Log.d(TAG, “cat”));

RxJava: unsubscribe

Subscription subs =

subs.unsubscribe();

RxJava: threading

Observable.from(myCats)

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

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

.subscribe(filteredPicture -> display(filteredPicture)

);

.subscribeOn(Schedulers.newThread())

.observeOn(AndroidSchedulers.mainThread())

RxJava: other ways of creating Observables

// emits on single item and completesObservable.just

// emits one item after a certain delayObservable.timer

.. plus many others, and you can create your own!

RxJava: demo with Retrofit & Meetup Streams

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

Meetup Streaming API

RxJava: demo with Meetup Streams

RxJava: demo with Retrofit & Meetup Streams

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

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>

RxJava: demo with Meetup Streams

RxJava: demo with Meetup Streams

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

Reactive in (Android) frontend VS backend

ANDROID

UsingRxJava

WHATDOPEOPLETHINKTHAT“BEINGREACTIVE”MEANS?

BACKEND

?

Evolution of server applications & user expectations

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)

Evolution of internet usage

The Reactive traits

Areactivecomputersystemmust Trait

Reacttoitsusers Responsive

Reacttofailureandstayavailable Resilient

Reacttovaryingloadconditions Elastic

Itscomponentsmustreacttoinputs Message-driven

The Reactive Manifesto

Responsive

ResilientElastic

MessageDriven

Reactive traits: Responsive

• Ahumanwhovisitsawebsite• Aclientwhichmakesarequesttoaserver• Aconsumerwhichcontactsaprovider• ...

AReactivesystemrespondstoinputsandusagefromitsuser.

Reactive traits: Elastic

• ScaleOUTandIN:usejusttherightamount• Elasticityreliesondistribution• Ensurereplicationincaseoffailure

Scaleondemandtoreacttovaryingload

Reactive traits: Resilient

Itdoesn'tmatterhowgreatyourapplicationisifitdoesn'twork.

FAULTTOLERANCE RESILIENCEVS

Reactive traits: Message Driven

ReactivesystemsdesignconcentratesonMessages.

Asynchronousmessagingenables:

• Separationbetweencomponents• Errorcontainment-avoidchainfailures• Domainmappingclosertoreality

The Reactive Manifesto, take 2

Responsive

ResilientElastic

MessageDriven

Why Functional Programming?

Moresupportiveofreasoningaboutproblemsinconcurrentandparallelisedapplications.

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

Reactive Patterns

DesignpatternstoachieveReactiveprinciples.

Toolkitsexisttoimplementthesepatterns.

Reactive Pattern: Simple Component Pattern

“Onecomponentshoulddoonlyonethingbutdoitinfull.Theaimistomaximisecohesionandminimisecouplingbetweencomponents.”

Reactive Pattern: Simple Component Pattern

Actor1

Actor3

Actor2

• containsstate• hasamailboxtoreceiveandsendmessages

• containsbehaviourlogic• hasasupervisor

ActormodelSupervisor

Reactive Patterns: Let it crash!

"Preferafullcomponentrestarttocomplexinternalfailurehandling".

• failureconditionsWILLoccur• theymightberareandhardtoreproduce• itismuchbettertostartcleanthantotrytorecover• …whichmightbeexpensiveanddifficult!

Reactive Patterns: Let it crash!

• Componentsshouldbeisolated-stateisnotshared• Componentsshouldhaveasupervisoranddelegatetoitsomeorallerrorhandling

• Thesupervisorcantransparentlyrestartthecomponent• Message-passingarchitecturesenforcestateconfinement,errorcontainmentandtransparency

Inpractice…

Reactive Patterns: Let it crash!

Actorsupervisionexample

Actor1

Actor2

Supervisor

WhateverException!

X

FixorRestart

Reactive Patterns: Let it crash!

• themachineonlyacceptsexactchange

Reactive Patterns: Let it crash!

Scenario1:Theuserinsertswrongamountofcoins

X

Error!

Reactive Patterns: Let it crash!

Scenario2:Themachineisoutofcoffeebeans

Failure!(!=error)

Reactive Patterns: Let it crash!

Reactive Patterns: Let it crash!

RandomlykillsinstancesoftheirAWSsystemtoensurethatnofailureispropagated.

BACKEND

?

BACKEND

Elasticity

Asyncrhonicity

Resilience

Supervision

Messagepassing

Stateencapsulation

Streams

Backpressure

Reactive in (Android) frontend VS backend

ANDROID

UsingRxJava

WHATDOPEOPLETHINKTHAT“BEINGREACTIVE”MEANS?

Reactive traits in Android?

CanweapplysomeoftheReactiveManifestoprinciplestoourAndroiddevelopment?

Reactive traits in Android?

Reactivetrait InAndroid?

Responsive Executeasmuchaspossibleasynchronously

Elastic —

Resilient Delegateriskystuffto(Intent)Servicesorisolatedcomponents

MessagepassingCommunicationviaResultReceiver

UsesomeeventBus

Reactive traits in Android?

…butIamsurethatwecantakethisfurther.

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.

Thanks!

@ticofab

All pictures belong to their respective authors

AMSTERDAM 11-12 MAY 2016