Reactive Android: RxJava & beyond Fabio Tiriticco / @ticofab AMSTERDAM 11-12 MAY 2016
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!
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
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>
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)
The Reactive traits
Areactivecomputersystemmust Trait
Reacttoitsusers Responsive
Reacttofailureandstayavailable Resilient
Reacttovaryingloadconditions Elastic
Itscomponentsmustreacttoinputs Message-driven
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
Why Functional Programming?
Moresupportiveofreasoningaboutproblemsinconcurrentandparallelisedapplications.
• encouragesuseofpurefunctions-minimisesideeffects• encouragesimmutability-statedoesn’tgetpassedaround• higher-orderfunctions-reusabilityandcomposability
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!
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?
Reactivetrait InAndroid?
Responsive Executeasmuchaspossibleasynchronously
Elastic —
Resilient Delegateriskystuffto(Intent)Servicesorisolatedcomponents
MessagepassingCommunicationviaResultReceiver
UsesomeeventBus
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.