Presented in Feb '18 at JUG NCR Meetup, New Delhi. https://www.meetup.com/Delhi-NCR-JUG/events/245487927/
Getting your feet wet withRxJavaRagunath Jawahar • @ragunathjawahar
View Slide
REACTIVE FUNCTIONAL
FUNCTIONAL• Functions are first-class citizens• Immutability• No side-effects• Referential transparency• Declarative• Favours concurrency
private boolean isDivisibleBy2(int number) {return number % 2 == 0;}Example 1
integers.stream().map(number -> isDivisibleBy2(number) ? "Even" : "Odd");Example 2
REACTIVE
REACTIVE• Responsive• Resilient• Elastic• Message Driven
REACTIVE• Speed Traps• Fire Alarms• Airbags• Autonomous Vehicles• Excel• GUI Systems• HystrixReal World Examples
~ Callbacks ~An imperative way to build reactive systems.
login(“username", “password", new Callback() {public void onSuccess(String authToken) {// Do something...}});
login(“username", “password", new Callback() {public void onSuccess(String authToken) {// Do something...}public void onFailure(Exception e) {// Show error message...}});
RxJava
A library for composing asynchronous and event-based programs using observable sequences forthe Java VM.
Where is it used?• Back-end to build highly scalable systems.• Front-end to create maintainable code.
RxJava• Primitives• Operators
Primitive - Observable• Produces events• Usually lazy• Can produce one, many or zero events•Serialized access
button.setOnClickListener(click -> doSomething());buttonClicksObservable.subscribe(click -> doSomething());CallbackRxJava
button.setOnClickListener(click ->api.authenticate(username, password, new Callback() {public void onSuccess(String authToken) {// Save Token}public void onLoginFailed(LoginException e) {// Show Error}}));Callback
buttonClicksObservable.flatMap(click -> api.authenticate(username, password)).onErrorReturn(null).subscribe(authToken ->if (authToken != null) saveToken(authToken) else showError(););RxJava
buttonClicksObservable.flatMap(click -> api.authenticate(username, password)).onErrorReturn(null).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(authToken ->if (authToken != null) saveToken(authToken) else showError(););RxJava
Observable - AnatomyDataErrorCompletion
Primitive - Subscriber• onNext(T)• onError(Throwable)• onComplete()
RxJava - Operators• Single Observable• Multiple Observable• Higher-Order Observables•Finite and infinite Observables (any of theabove)
Marble Diagrams
filter
map
debounce
delay
interval
amb
merge
combineLatest
zip
flatMap
onError*
retry*
Error Handling• Exceptions are normal• Error handling operators• Retry operators
Declarative Threading• Using Schedulers• subscribeOn(Scheduler)• observeOn(Scheduler)
Debugging• Could be a pain • Use doOn* operators to inspect thepipeline• Traceur (RxJava 2)
Testing• Mockito• Subjects / Relays
Further ReadingAndré Staltz
Questions?