SlideShare une entreprise Scribd logo
1  sur  46
- Reactive Extensions first introduced by Microsoft in 2009 for .NET
- Has been ported on most platforms and languages
History
Proved in production
“Unless you can model the entire system of your
app in a synchronous fashion, having a single
asynchronous source will ultimately break the
traditional imperative style of programming we’re
used to.”
Advantages
- Simplifies the ability to chain async operations.
- Surfaces errors sooner.
- Easy threading
- Helps reduce the need for state variables that can introduce bugs.
Disadvantages
- The API surface area is large. consequently, the learning curve is steep
What is RxJava?
RxJava is Reactive Extensions for the JVM - a library for
composing asynchronous and event-based programs using
Observable sequences for the Java VM
What is RxJava?
In other words we are pushing data instead of pulling it
without worrying about threads.
On top of that you are given an amazing toolbox of
functions to combine create and filter the streams
How to think in RxJava
Should I use RxJava 2 instead of 1?
YES!
- Mar 2018 - end of RxJava 1 support
- Better performance
- Lower memory consumption
- Can’t use null
- Backpressure (Flowable)
Iterable vs Observable, seems familiar?
Event Iterable Observable
retrieve data T next() onNext(T)
discover error throw Exception onError(Exception)
complete !hasNext() onCompleted()
transform fromIterable() toList()
Observables and Observers
The basic building blocks of reactive code are Observables
(Producer) and Observers (Consumer).
The Observable object is the one who does the job.
An Observer consumes the items emitted by the Observable.
An Observable calls Observer#onNext() for every item, followed
by either Observer#onComplete() or Observer#onError().
Observables and Friends
- Flowable: 0..N flows, supporting reactive streams and backpressure
- Observable: 0..N flows, no backpressure
- Single: a flow of exactly 1 item or am error
- Completable: a flow without items but only a completion or error signal
- Maybe: a flow with no items, exactly one item or an error
Disposables
Disposables represents the link between your Observable and
your Subscriber
Disposable d = Observable.timer(0, TimeUnit.SECONDS).subscribe(aLong -> {});
//Adding the disposable to CompositeDisposable
disposables.add(d);
//You can remove a disposable using delete method
disposables.delete(d);
//The container can be later reused
disposables.clear();
//The container cannot be reused
disposables.dispose();
Creating Observable
Let's take the most basic example to understand how
this is structured.
Observable.just(“Hello!”)
Creating Observable from async (The ugly
way)
Observable<Movie> movieObservable = Observable.create(
new ObservableOnSubscribe<Todo>() {
@Override
public void subscribe(ObservableEmitter<Movie> emitter)
throws
Exception {
try {
// Fetches Movie objects from the network, database, etc.
List<Movie> movies = getMovies();
for (Movie movie : movies) {
emitter.onNext(movie);
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
}
});
When we want to create an Observable using async code
Creating Observable using lambda
Observable<Movie> movieObservable = Observable.create(emitter -> {
try {
// Fetches Movie objects from the network, database, etc.
List<Movie> movies = getMovies();
for (Movie movie : movies) {
emitter.onNext(movie);
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
});
Lambda expressions is only a “new” way of doing the same thing we
always been able to do but in a cleaner and less wordy the new way of on
how to use anonymous inner classes.
Defining Observers
Let's take the most basic example to understand how
this is structured.
movieObservable.subscribe(new Observer<String>() {
@Override
public void onNext(String s) { System.out.println("onNext: " + s); }
@Override
public void onCompleted() { System.out.println("done!"); }
@Override
public void onError(Throwable e) { }
});
public interface Observer<T> {
void onNext(T t);
void onCompleted();
void onError(Throwable e);
}
Operators
There is 248 operators we will focus on the common
- map()
- flatmap()
- filter()
- distinct()
- take()
- count()
Operators - Map
Transform the items emitted by an Observable by
applying a function to each item
Operators - Map - Example
Observable.just("Hello!")
.map(new Func1<String, String>() {
@Override
public String call(String s) {
return s + " Dan";
}
})
.subscribe(s -> System.out.println(s));
Observable.just("Hello!")
.map(s -> s + " Dan")
.subscribe(s -> System.out.println(s));
Operators - Flatmap
- Transforms the items emitted by an Observable
into Observables, then flatten the emissions from
those into a single Observable (no order)
Operators - Flatmap - Example
Observable.just("Hello!")
.flatMap(new Func1<List<String>, Observable<String>>() {
@Override
public Observable<String> call(List<String> urls) {
return Observable.from(urls);
}
})
.subscribe(url -> System.out.println(url));
Observable.just("Hello!")
.flatMap(urls -> Observable.from(urls))
.subscribe(title -> System.out.println(title));
Flatmap vs Map
- Map returns an object of type T while FlatMap returns an Observable<T>.
- FlatMap - It basically merges an observable sequence of observable
sequences into a single observable sequence.
Operators - Filter
- Emits the same items it received, only if it passes
the boolean check (predicate)
Operators - Filter - Example
Observable.just("Hello!")
.flatMap(urls -> Observable.from(urls))
.flatMap(url -> getTitle(url))
.filter(title -> title != null)
.subscribe(url -> System.out.println(url));
Operators - Reduce
- The Distinct operator filters an Observable by only
allowing items through that have not already been
emitted.
Operators - Reduce - Example
Observable.just("Hello!")
.flatMap(urls -> Observable.from(urls))
.flatMap(url -> getTitle(url))
.distinct(title -> title.startsWith(“Hell”)
.subscribe(url -> System.out.println(url));
Operators - Take
- Emits only the first n items emitted by an Observable
Operators - Take - Example
Observable.just("Hello!")
.flatMap(urls -> Observable.from(urls))
.flatMap(url -> getTitle(url))
.filter(title -> title != null)
.take(5)
.subscribe(title -> System.out.println(title));
Operators - Zip
- Emits when it has all the values to zip
Error handling
- onError() is called if an exception is thrown
at any time.
- The operators do not have to handle the
exception
public interface Observer<T> {
void onNext(T t);
void onCompleted();
void onError(Throwable e);
}
Error Operators
- onErrorResumeNext()
- onErrorReturn()
- onExceptionResumeNext()
- retry()
- retryWhen()
Multithread like a
BOSS
Schedulers.io()
Unbounded thread pool
Schedulers.computation()
Bounded thread pool with size up to the number of processors
available.
Multithread Example
Observable.just("long", "longer", "longest")
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.map(String::length)
.filter(length -> length == 6)
.subscribe(length -> System.out.println("item length " + length));
Multiple REST Calls
Observable<JsonObject> userObservable = repo
.create(User.class)
.getUser(loginName)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
Observable<JsonArray> eventsObservable = repo
.create(Event.class)
.listEvents(loginName)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
Retrofit repo = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
Let’s first setup two observables for the two network requests
below:
Zip magic
Observable<UserAndEvents> combined = Observable.zip(userObservable,
eventsObservable, new Func2<JsonObject, JsonArray, UserAndEvents>() {
@Override
public UserAndEvents call(JsonObject jsonObject, JsonArray jsonElements) {
return new UserAndEvents(jsonObject, jsonElements);
}
});
We use RxJava’s zip method to combine
our two Observables and wait for them to
complete before creating a new Observable.
Consume response
combined.subscribe(new Subscriber<UserAndEvents>() {
...
@Override
public void onNext(UserAndEvents o) {
// You can access the results of the
// two observabes via the POJO now
}
});
Finally let’s call the subscribe method on our new
combined Observable:
Login case
// force-disable the button
submitButton.setEnabled(false);
emailChangeObservable = RxTextView.textChangeEvents(email);
passwordChangeObservable = RxTextView.textChangeEvents(password);
Observable.combineLatest(emailChangeObservable, passwordChangeObservable,
(emailObservable, passwordObservable) -> {
boolean emailCheck = emailObservable.text().length() >= 3;
boolean passwordCheck = passwordObservable.text().length() >= 3;
return emailCheck && passwordCheck;
}).subscribe(aBoolean -> {
submitButton.setEnabled(aBoolean);
});
A common case that appears in almost every app that requires you to
have an account is the Sign In screen. I wanted to set up form validation
so that only when all fields are valid then a Sign In button would be
enabled.
Repository pattern example
public Observable<List<Repository>> getRepositories() {
Observable<List<Repository>> remote = getRemoteRepositories();
Observable<List<Repository>> local = getLocalRepositories();
return Observable.concat(local, remote);
}
What about Unit Testing?
What about Testings?
@Test
public void shouldLoadTwoUsers() throw Exception {
TestSubscriber<User> testSubscriber = new TestSubscriber<>();
databaseHelper.loadUser().subscribe(testSubscriber);
testSubscriber.assertNoErrors();
testSubscriber.assertReceivedOnNext(Arrays.asList(user1, user2))
}
TestSubscriber is a helper class provided by RxJava that we can use for
unit testing, to perform assertions, inspect received events, or wrap a
mocked Subscriber.
@Test
public void testValueCont() {
Observable.just("Hello","RxJava","Testing").subscribe(wordListTestSubscriber);
wordListTestSubscriber.assertValueCount(3);
}
Questions?Questions :)

Contenu connexe

Tendances

JPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APIJPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APItvaleev
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8 Dori Waldman
 
Streams processing with Storm
Streams processing with StormStreams processing with Storm
Streams processing with StormMariusz Gil
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
Evolutionary Testing for Crash Reproduction
Evolutionary Testing for Crash ReproductionEvolutionary Testing for Crash Reproduction
Evolutionary Testing for Crash ReproductionAnnibale Panichella
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
Lua: the world's most infuriating language
Lua: the world's most infuriating languageLua: the world's most infuriating language
Lua: the world's most infuriating languagejgrahamc
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Ben Lesh
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster DivingRonnBlack
 
Confitura 2018 — Apache Beam — Promyk Nadziei Data Engineera
Confitura 2018 — Apache Beam — Promyk Nadziei Data EngineeraConfitura 2018 — Apache Beam — Promyk Nadziei Data Engineera
Confitura 2018 — Apache Beam — Promyk Nadziei Data EngineeraPiotr Wikiel
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopSaša Tatar
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQLPeter Eisentraut
 

Tendances (20)

JPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APIJPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream API
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
 
Streams processing with Storm
Streams processing with StormStreams processing with Storm
Streams processing with Storm
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Storm Anatomy
Storm AnatomyStorm Anatomy
Storm Anatomy
 
Evolutionary Testing for Crash Reproduction
Evolutionary Testing for Crash ReproductionEvolutionary Testing for Crash Reproduction
Evolutionary Testing for Crash Reproduction
 
Pragmatic sbt
Pragmatic sbtPragmatic sbt
Pragmatic sbt
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Web streams
Web streamsWeb streams
Web streams
 
Lua: the world's most infuriating language
Lua: the world's most infuriating languageLua: the world's most infuriating language
Lua: the world's most infuriating language
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Go memory
Go memoryGo memory
Go memory
 
Deep Dumpster Diving
Deep Dumpster DivingDeep Dumpster Diving
Deep Dumpster Diving
 
Confitura 2018 — Apache Beam — Promyk Nadziei Data Engineera
Confitura 2018 — Apache Beam — Promyk Nadziei Data EngineeraConfitura 2018 — Apache Beam — Promyk Nadziei Data Engineera
Confitura 2018 — Apache Beam — Promyk Nadziei Data Engineera
 
Terraform day02
Terraform day02Terraform day02
Terraform day02
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
Streams in Node.js
Streams in Node.jsStreams in Node.js
Streams in Node.js
 

Similaire à Intro to Reactive Thinking and RxJava 2

RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVMNetesh Kumar
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptProgscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptJohn Stevenson
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIJörn Guy Süß JGS
 
Airflow tutorials hands_on
Airflow tutorials hands_onAirflow tutorials hands_on
Airflow tutorials hands_onpko89403
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupHenrik Engström
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongJDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongPROIDEA
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixTracy Lee
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupDavid Barreto
 

Similaire à Intro to Reactive Thinking and RxJava 2 (20)

RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Rxandroid
RxandroidRxandroid
Rxandroid
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptProgscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
Airflow tutorials hands_on
Airflow tutorials hands_onAirflow tutorials hands_on
Airflow tutorials hands_on
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongJDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMix
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
G pars
G parsG pars
G pars
 
React native
React nativeReact native
React native
 

Dernier

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Dernier (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Intro to Reactive Thinking and RxJava 2

  • 1. - Reactive Extensions first introduced by Microsoft in 2009 for .NET - Has been ported on most platforms and languages History
  • 3. “Unless you can model the entire system of your app in a synchronous fashion, having a single asynchronous source will ultimately break the traditional imperative style of programming we’re used to.”
  • 4. Advantages - Simplifies the ability to chain async operations. - Surfaces errors sooner. - Easy threading - Helps reduce the need for state variables that can introduce bugs.
  • 5. Disadvantages - The API surface area is large. consequently, the learning curve is steep
  • 6. What is RxJava? RxJava is Reactive Extensions for the JVM - a library for composing asynchronous and event-based programs using Observable sequences for the Java VM
  • 7. What is RxJava? In other words we are pushing data instead of pulling it without worrying about threads. On top of that you are given an amazing toolbox of functions to combine create and filter the streams
  • 8. How to think in RxJava
  • 9.
  • 10. Should I use RxJava 2 instead of 1? YES! - Mar 2018 - end of RxJava 1 support - Better performance - Lower memory consumption - Can’t use null - Backpressure (Flowable)
  • 11. Iterable vs Observable, seems familiar? Event Iterable Observable retrieve data T next() onNext(T) discover error throw Exception onError(Exception) complete !hasNext() onCompleted() transform fromIterable() toList()
  • 12. Observables and Observers The basic building blocks of reactive code are Observables (Producer) and Observers (Consumer). The Observable object is the one who does the job. An Observer consumes the items emitted by the Observable. An Observable calls Observer#onNext() for every item, followed by either Observer#onComplete() or Observer#onError().
  • 13. Observables and Friends - Flowable: 0..N flows, supporting reactive streams and backpressure - Observable: 0..N flows, no backpressure - Single: a flow of exactly 1 item or am error - Completable: a flow without items but only a completion or error signal - Maybe: a flow with no items, exactly one item or an error
  • 14. Disposables Disposables represents the link between your Observable and your Subscriber Disposable d = Observable.timer(0, TimeUnit.SECONDS).subscribe(aLong -> {}); //Adding the disposable to CompositeDisposable disposables.add(d); //You can remove a disposable using delete method disposables.delete(d); //The container can be later reused disposables.clear(); //The container cannot be reused disposables.dispose();
  • 15.
  • 16. Creating Observable Let's take the most basic example to understand how this is structured. Observable.just(“Hello!”)
  • 17. Creating Observable from async (The ugly way) Observable<Movie> movieObservable = Observable.create( new ObservableOnSubscribe<Todo>() { @Override public void subscribe(ObservableEmitter<Movie> emitter) throws Exception { try { // Fetches Movie objects from the network, database, etc. List<Movie> movies = getMovies(); for (Movie movie : movies) { emitter.onNext(movie); } emitter.onComplete(); } catch (Exception e) { emitter.onError(e); } } }); When we want to create an Observable using async code
  • 18. Creating Observable using lambda Observable<Movie> movieObservable = Observable.create(emitter -> { try { // Fetches Movie objects from the network, database, etc. List<Movie> movies = getMovies(); for (Movie movie : movies) { emitter.onNext(movie); } emitter.onComplete(); } catch (Exception e) { emitter.onError(e); } }); Lambda expressions is only a “new” way of doing the same thing we always been able to do but in a cleaner and less wordy the new way of on how to use anonymous inner classes.
  • 19. Defining Observers Let's take the most basic example to understand how this is structured. movieObservable.subscribe(new Observer<String>() { @Override public void onNext(String s) { System.out.println("onNext: " + s); } @Override public void onCompleted() { System.out.println("done!"); } @Override public void onError(Throwable e) { } }); public interface Observer<T> { void onNext(T t); void onCompleted(); void onError(Throwable e); }
  • 20. Operators There is 248 operators we will focus on the common - map() - flatmap() - filter() - distinct() - take() - count()
  • 21. Operators - Map Transform the items emitted by an Observable by applying a function to each item
  • 22. Operators - Map - Example Observable.just("Hello!") .map(new Func1<String, String>() { @Override public String call(String s) { return s + " Dan"; } }) .subscribe(s -> System.out.println(s)); Observable.just("Hello!") .map(s -> s + " Dan") .subscribe(s -> System.out.println(s));
  • 23. Operators - Flatmap - Transforms the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable (no order)
  • 24. Operators - Flatmap - Example Observable.just("Hello!") .flatMap(new Func1<List<String>, Observable<String>>() { @Override public Observable<String> call(List<String> urls) { return Observable.from(urls); } }) .subscribe(url -> System.out.println(url)); Observable.just("Hello!") .flatMap(urls -> Observable.from(urls)) .subscribe(title -> System.out.println(title));
  • 25. Flatmap vs Map - Map returns an object of type T while FlatMap returns an Observable<T>. - FlatMap - It basically merges an observable sequence of observable sequences into a single observable sequence.
  • 26. Operators - Filter - Emits the same items it received, only if it passes the boolean check (predicate)
  • 27. Operators - Filter - Example Observable.just("Hello!") .flatMap(urls -> Observable.from(urls)) .flatMap(url -> getTitle(url)) .filter(title -> title != null) .subscribe(url -> System.out.println(url));
  • 28. Operators - Reduce - The Distinct operator filters an Observable by only allowing items through that have not already been emitted.
  • 29. Operators - Reduce - Example Observable.just("Hello!") .flatMap(urls -> Observable.from(urls)) .flatMap(url -> getTitle(url)) .distinct(title -> title.startsWith(“Hell”) .subscribe(url -> System.out.println(url));
  • 30. Operators - Take - Emits only the first n items emitted by an Observable
  • 31. Operators - Take - Example Observable.just("Hello!") .flatMap(urls -> Observable.from(urls)) .flatMap(url -> getTitle(url)) .filter(title -> title != null) .take(5) .subscribe(title -> System.out.println(title));
  • 32. Operators - Zip - Emits when it has all the values to zip
  • 33. Error handling - onError() is called if an exception is thrown at any time. - The operators do not have to handle the exception public interface Observer<T> { void onNext(T t); void onCompleted(); void onError(Throwable e); }
  • 34. Error Operators - onErrorResumeNext() - onErrorReturn() - onExceptionResumeNext() - retry() - retryWhen()
  • 35. Multithread like a BOSS Schedulers.io() Unbounded thread pool Schedulers.computation() Bounded thread pool with size up to the number of processors available.
  • 36. Multithread Example Observable.just("long", "longer", "longest") .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .map(String::length) .filter(length -> length == 6) .subscribe(length -> System.out.println("item length " + length));
  • 37. Multiple REST Calls Observable<JsonObject> userObservable = repo .create(User.class) .getUser(loginName) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()); Observable<JsonArray> eventsObservable = repo .create(Event.class) .listEvents(loginName) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()); Retrofit repo = new Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); Let’s first setup two observables for the two network requests below:
  • 38. Zip magic Observable<UserAndEvents> combined = Observable.zip(userObservable, eventsObservable, new Func2<JsonObject, JsonArray, UserAndEvents>() { @Override public UserAndEvents call(JsonObject jsonObject, JsonArray jsonElements) { return new UserAndEvents(jsonObject, jsonElements); } }); We use RxJava’s zip method to combine our two Observables and wait for them to complete before creating a new Observable.
  • 39. Consume response combined.subscribe(new Subscriber<UserAndEvents>() { ... @Override public void onNext(UserAndEvents o) { // You can access the results of the // two observabes via the POJO now } }); Finally let’s call the subscribe method on our new combined Observable:
  • 40. Login case // force-disable the button submitButton.setEnabled(false); emailChangeObservable = RxTextView.textChangeEvents(email); passwordChangeObservable = RxTextView.textChangeEvents(password); Observable.combineLatest(emailChangeObservable, passwordChangeObservable, (emailObservable, passwordObservable) -> { boolean emailCheck = emailObservable.text().length() >= 3; boolean passwordCheck = passwordObservable.text().length() >= 3; return emailCheck && passwordCheck; }).subscribe(aBoolean -> { submitButton.setEnabled(aBoolean); }); A common case that appears in almost every app that requires you to have an account is the Sign In screen. I wanted to set up form validation so that only when all fields are valid then a Sign In button would be enabled.
  • 41. Repository pattern example public Observable<List<Repository>> getRepositories() { Observable<List<Repository>> remote = getRemoteRepositories(); Observable<List<Repository>> local = getLocalRepositories(); return Observable.concat(local, remote); }
  • 42. What about Unit Testing?
  • 43. What about Testings? @Test public void shouldLoadTwoUsers() throw Exception { TestSubscriber<User> testSubscriber = new TestSubscriber<>(); databaseHelper.loadUser().subscribe(testSubscriber); testSubscriber.assertNoErrors(); testSubscriber.assertReceivedOnNext(Arrays.asList(user1, user2)) } TestSubscriber is a helper class provided by RxJava that we can use for unit testing, to perform assertions, inspect received events, or wrap a mocked Subscriber. @Test public void testValueCont() { Observable.just("Hello","RxJava","Testing").subscribe(wordListTestSubscriber); wordListTestSubscriber.assertValueCount(3); }
  • 44.
  • 45.