Reactive Android: RxJava & beyond Fabio Tiriticco / @ticofab AMSTERDAM 11-12 MAY 2016
A little info about myself Android	Engineer Scala	Engineer
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 “I	was	thinking	of	using	Node.js,	but maybe	I	can	build	it	with	Reactive.” “Thanks	for	running	a	meetup	about	React.js”
Reactive Confusion • The	concept	of	“Reactive”	has	common basis	but	slightly	different	meanings	in each	domain • Most	of	us	think	that	Reactive	==	React.js Two	main	observations:
Reactive in (Android) frontend VS backend ANDROID Using	RxJava WHAT	DO	PEOPLE	THINK	THAT “BEING	REACTIVE”	MEANS? BACKEND ?
Hello, RxJava! • Asynchronous	programming • Observable	streams Open	source	libraries	for
Hello, RxJava! Mobile	engineering	is	hard	and	there	are	high	expectations. RxJava	is	cool	because • it	makes	it	super	easy	to	switch	between	threads • lets	us	deal	with	data	as	a	stream • brings	us	some	degree	of	functional	programming.
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(); Retrolamba	plugin	for Android	<	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 T onError, // throwable onComplete // 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 completes Observable.just // emits one item after a certain delay Observable.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 -> R flatMap: 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 Using	RxJava WHAT	DO	PEOPLE	THINK	THAT “BEING	REACTIVE”	MEANS? BACKEND ?
Evolution of server applications & user expectations 2006 2016 Servers ~10 The	sky	is	the	limit. Response	time seconds milliseconds Offline	maintenance hours what? Data	amount Gigabytes Petabytes Machines Single	core,	little	distribution Must	work	across	async boundaries	(location,	threads) Kind	of	data Request	-	response Streams	(endless)
Evolution of internet usage
The Reactive traits A	reactive	computer	system	must Trait React	to	its	users Responsive React	to	failure	and	stay	available Resilient React	to	varying	load	conditions Elastic Its	components	must	react	to	inputs Message-driven
The Reactive Manifesto Responsive ResilientElastic Message	Driven
Reactive traits: Responsive • A	human	who	visits	a	website • A	client	which	makes	a	request	to	a	server • A	consumer	which	contacts	a	provider • .	.	. A	Reactive	system	responds	to	inputs	and	usage	from	its	user.
Reactive traits: Elastic • Scale	OUT	and	IN:	use	just	the	right	amount • Elasticity	relies	on	distribution • Ensure	replication	in	case	of	failure Scale	on	demand	to	react	to	varying	load
Reactive traits: Resilient It	doesn't	matter	how	great	your	application	is	if	it	doesn't	work. FAULT	TOLERANCE RESILIENCEVS
Reactive traits: Message Driven Reactive	systems	design	concentrates	on	Messages. Asynchronous	messaging	enables: • Separation	between	components • Error	containment	-	avoid	chain	failures • Domain	mapping	closer	to	reality
The Reactive Manifesto, take 2 Responsive ResilientElastic Message	Driven
Why Functional Programming? More	supportive	of	reasoning	about	problems	in	concurrent	and parallelised	applications. • encourages	use	of	pure	functions	-	minimise	side	effects • encourages	immutability	-	state	doesn’t	get	passed	around • higher-order	functions	-	reusability	and	composability
Reactive Patterns Design	patterns	to	achieve	Reactive	principles. Toolkits	exist	to	implement	these	patterns.
Reactive Pattern: Simple Component Pattern “One	component	should	do	only	one	thing	but	do	it	in	full.	The	aim	is	to maximise	cohesion	and	minimise	coupling	between	components.”
Reactive Pattern: Simple Component Pattern Actor	1	Actor	3 Actor	2 • contains	state • has	a	mailbox	to	receive and	send	messages • contains	behaviour	logic • has	a	supervisor Actor	model Supervisor
Reactive Patterns: Let it crash! "Prefer	a	full	component	restart	to	complex	internal	failure	handling". • failure	conditions	WILL	occur • they	might	be	rare	and	hard	to	reproduce • it	is	much	better	to	start	clean	than	to	try	to	recover • …which	might	be	expensive	and	difficult!
Reactive Patterns: Let it crash! • Components	should	be	isolated	-	state	is	not	shared • Components	should	have	a	supervisor	and	delegate	to	it some	or	all	error	handling • The	supervisor	can	transparently	restart	the	component • Message-passing	architectures	enforce	state confinement,	error	containment	and	transparency In	practice…
Reactive Patterns: Let it crash! Actor	supervision	example Actor	1	Actor	2 Supervisor WhateverException! X Fix	or Restart
Reactive Patterns: Let it crash! • the	machine	only accepts	exact	change
Reactive Patterns: Let it crash! Scenario	1: The	user	inserts	wrong amount	of	coins X Error!
Reactive Patterns: Let it crash! Scenario	2: The	machine	is	out	of coffee	beans Failure! (	!=	error)
Reactive Patterns: Let it crash!
Reactive Patterns: Let it crash! Randomly	kills	instances of	their	AWS	system	to ensure	that	no	failure	is propagated.
BACKEND ? BACKEND Elasticity Asyncrhonicity Resilience Supervision Message	passing State	encapsulation Streams Backpressure … Reactive in (Android) frontend VS backend ANDROID Using	RxJava WHAT	DO	PEOPLE	THINK	THAT “BEING	REACTIVE”	MEANS?
Reactive traits in Android? Can	we	apply	some	of	the	Reactive	Manifesto principles	to	our	Android	development?
Reactive traits in Android? Reactive	trait In	Android? Responsive Execute	as	much	as	possible	asynchronously Elastic — Resilient Delegate	risky	stuff	to	(Intent)Services	or	isolated	components Message	passing Communication	via	ResultReceiver Use	some	event	Bus
Reactive traits in Android? …but	I	am	sure	that	we	can	take	this	further.
Resources https://github.com/ReactiveX/RxJava/wiki RxJava	documentation	&	wiki http://rxmarbles.com RxJava	operators	explained	visually http://www.reactivemanifesto.org The	reactive	manifesto https://www.youtube.com/watch?v=fNEZtx1VVAk https://www.youtube.com/watch?v=ryIAibBibQI https://www.youtube.com/watch?v=JvbUF33sKf8 The	Reactive	Revealed	series:	awesome	webinars	by	the creators	of	the	Reactive	Manifesto. https://www.manning.com/books/reactive-design-patterns https://www.youtube.com/watch?v=nSfXcSWq0ug Reactive	design	patterns,	book	and	webinar.
Thanks! @ticofab All pictures belong to their respective authors AMSTERDAM 11-12 MAY 2016

Reactive Android: RxJava and beyond