SlideShare a Scribd company logo
1 of 111
Download to read offline
MADRID · NOV 27-28 · 2015
RxJava in practice
Javier Gamarra
MADRID · NOV 27-28 · 2015
http://kcy.me/29crj (slides)
&
http://kcy.me/296bu (commits)
MADRID · NOV 27-28 · 2015
Environment
Eclipse | Android Studio (RxAndroid)
RxJava.jar
[Java 8] || [Retrolambda] :P
MADRID · NOV 27-28 · 2015
Environment
Android Studio:
compile 'io.reactivex:rxandroid:1.0.1'
compile 'io.reactivex:rxjava:1.0.16'
Eclipse:
● Copy jars to lib/ and add jar in project
MADRID · NOV 27-28 · 2015
Github
● http://kcy.me/296bu
● koans
● código
● commit a commit
● Podéis preguntarme en cualquier
momento
MADRID · NOV 27-28 · 2015
Who?
Javier Gamarra / @nhpatt
@liferay
@cyliconvalley / @agilespain
MADRID · NOV 27-28 · 2015
Ask!
Please? Pretty please? Please pretty please with sugar on top?
MADRID · NOV 27-28 · 2015
Background?
MADRID · NOV 27-28 · 2015
Why?
MADRID · NOV 27-28 · 2015
Why? (in java)
multithreading is hard
futures are complicated
callbacks are hell
MADRID · NOV 27-28 · 2015
Rx comes to the rescue!
MADRID · NOV 27-28 · 2015
a library
to represent any operation as an
asynchronous data stream
on any thread,
declaratively composed,
and consumed by multiple objects
MADRID · NOV 27-28 · 2015
a library
MADRID · NOV 27-28 · 2015
A library?
Extensions to .NET framework
Netflix
MADRID · NOV 27-28 · 2015
Libraries are tools
If all you have is a hammer, everything looks like a nail
MADRID · NOV 27-28 · 2015
a library to model
Observables & Subscribers
MADRID · NOV 27-28 · 2015
Observables and Subscribers
An Observable emits items.
A Subscriber consumes those items.
MADRID · NOV 27-28 · 2015
Observer pattern?
MADRID · NOV 27-28 · 2015
My very first observable
Observable<String> myObs = Observable. create(new Observable.
OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext( "Hi!");
subscriber.onCompleted();
}
});
MADRID · NOV 27-28 · 2015
My very first subscriber
Subscriber<String> mySubs = new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onNext(String s) {
System. out.println(s);
}
};
MADRID · NOV 27-28 · 2015
My very first subscription
myObs.subscribe(mySubs);
MADRID · NOV 27-28 · 2015
A bit verbose...
Let’s simplify with Java8 and RxJava
● lamdbas
● Observable.just
● .subscribe()
MADRID · NOV 27-28 · 2015
That’s better...
Observable
.just("Hi!")
.subscribe(System.out::println);
MADRID · NOV 27-28 · 2015
Why?
More than the observer pattern
● Observables only emit when someone
listening
● OnFinished
● OnError
MADRID · NOV 27-28 · 2015
Let’s use those differences
subscribe admits 3 parameters
● OnNext
● OnFinished
● OnError
MADRID · NOV 27-28 · 2015
You said “items”
Observable.from admits a list of elements
MADRID · NOV 27-28 · 2015
Ok, let’s recap…
Iterators?
MADRID · NOV 27-28 · 2015
Iterators?
● Iterators are pull and synchronous
● Subscribers are push and asynchronous
MADRID · NOV 27-28 · 2015
to represent any operation as an
“asynchronous data stream”
MADRID · NOV 27-28 · 2015
Everything is a stream
MADRID · NOV 27-28 · 2015
Everything is a stream
We can model everything as a
stream
MADRID · NOV 27-28 · 2015
Everything is a stream
A network call is also a stream
Like using retrofit with this API
MADRID · NOV 27-28 · 2015
“declaratively composed”
MADRID · NOV 27-28 · 2015
Operators
MADRID · NOV 27-28 · 2015
Operators
Transform a stream
rxmarbles and android app
MADRID · NOV 27-28 · 2015
Operators
Map
MADRID · NOV 27-28 · 2015
Map
List<String> severalThings = Arrays.asList("1", "2");
Observable.from(severalThings)
.map((s) -> “Element “ + s)
.subscribe(System.out::println);
MADRID · NOV 27-28 · 2015
Map
We can return another type:
List<String> severalThings = Arrays.asList("1", "2");
Observable.from(severalThings)
.map(Integer::valueOf)
.subscribe(System.out::println);
MADRID · NOV 27-28 · 2015
Map
Let’s do the same with our repos…
And… I can’t because we return a List
And using Observable.from… NOP
MADRID · NOV 27-28 · 2015
Flatmap
Flatmap
Obs -> elements
MADRID · NOV 27-28 · 2015
Flatmap
service.listRepos("nhpatt")
.flatMap(Observable::from)
.map(Repo::getName)
.map((s) -> s.replace("-", " "))
.subscribe(System.out::println);
MADRID · NOV 27-28 · 2015
Flatmap
Concatmap -> ordered flatmap
MADRID · NOV 27-28 · 2015
Filter
service.listRepos("nhpatt")
.flatMap(Observable::from)
.map(Repo::getName)
.map((s) -> s.replace("-", " "))
.filter((s) -> s.startsWith("Android"))
.subscribe(System.out::println);
MADRID · NOV 27-28 · 2015
Scan & old code
service.listRepos("nhpatt")
.flatMap(Observable::from)
.map(Repo::getName)
.map((s) -> s.replace("-", " "))
.filter((s) -> s.startsWith("Android"))
.take(2)
.map(String::length)
.scan((x, y) -> x * y)
.subscribe(System.out::println);
MADRID · NOV 27-28 · 2015
Scan & old code
(l) -> {
int result = 0;
int i = 0;
int oldLength = 1;
for (Repo repo : l) {
String name = repo.getName();
String replacedName = name.replace( "-", " ");
if (replacedName.startsWith( "Android") && i < 2) {
result = replacedName.length() * oldLength;
oldLength = result;
System.out.println(result);
i++;
}
}
return result;
MADRID · NOV 27-28 · 2015
Operators
● merge
● flatMap
● zip
Nice things™ : parallel jobs!
MADRID · NOV 27-28 · 2015
Zipping requests
Observable<Repo> repo = service.listRepos("nhpatt")
.flatMap(Observable::from)
.take(1);
Observable<Commit> commit = service.listCommits("nhpatt",
"Android")
.flatMap(Observable::from)
.take(1);
Observable.zip(repo, commit, this::updateCommit).subscribe
(repo1 -> {
System.out.println(repo1.getCommit().getUrl());
});
MADRID · NOV 27-28 · 2015
Operators
Amazing documentation
● Async
● Blocking
● Combining
● Conditional
● Error handling
● Filtering
● Mathematical
● Creation
● String
● Transforming
● Utility
MADRID · NOV 27-28 · 2015
Subscribers are asynchronous?
No, not really
MADRID · NOV 27-28 · 2015
“on any thread”
MADRID · NOV 27-28 · 2015
Schedulers!
MADRID · NOV 27-28 · 2015
Schedulers
I define an API declaratively
and later in the implementation run it:
asynchronously
or in a separate Thread
or in a Threadpool
or synchronously
...
MADRID · NOV 27-28 · 2015
Schedulers
.subscribeOn(Schedulers...)
.observeOn(Schedulers...)
● io
● computation
● newThread
● trampoline
● test
MADRID · NOV 27-28 · 2015
Schedulers
service.listRepos("nhpatt")
.subscribeOn(Schedulers.immediate())
.observeOn(Schedulers.immediate())
.subscribe(System.out::println);
MADRID · NOV 27-28 · 2015
Schedulers
RxJava operators have default threads
Interval?
MADRID · NOV 27-28 · 2015
Use cases?
MADRID · NOV 27-28 · 2015
Use cases
● Autocomplete with debounce | sample…
● Accumulate calls with buffer...
● Polling with timeout | window…
● Form Validation with combineLatest…
● Retrieve data fast from cache | network call with
concat | merge…
● Button click with delay, listen on other thread
MADRID · NOV 27-28 · 2015
Android?
MADRID · NOV 27-28 · 2015
Why?
MADRID · NOV 27-28 · 2015
Why? (in android)
Main/UI thread and background problem
● Can’t do heavy tasks on UI
● Can’t update view on background
● AsyncTasks are bad
● Handlers can leak
MADRID · NOV 27-28 · 2015
How RxAndroid helps?
MADRID · NOV 27-28 · 2015
Android schedulers
service.listRepos("nhpatt")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(newRepos -> {
repos.addAll(newRepos);
adapter.notifyDataSetChanged();
});
MADRID · NOV 27-28 · 2015
Orientation Problem
Orientation Problem
● onCreate gets called again
● state is lost
MADRID · NOV 27-28 · 2015
Orientation Problem
Programmer’s job:
● Store/Restore state
● Restore view
● Call again the user task?
● Wait until it finishes?
MADRID · NOV 27-28 · 2015
How RxAndroid helps?
MADRID · NOV 27-28 · 2015
Orientation Problem
Observable is easy to persist
(retain | singleton)
Observable can continue (cache and retry)
RxLifecycle
MADRID · NOV 27-28 · 2015
Orientation Problem
Observable<List<Repo>> github = RetrofitService.
getGithub()
.listRepos("nhpatt")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.cache();
MADRID · NOV 27-28 · 2015
More Android
Lifecycle (RxLifecyle)
Views (RxBinding)
MADRID · NOV 27-28 · 2015
But...
MADRID · NOV 27-28 · 2015
But...
Subscriptions leak memory :’(
We have to call to unsubscribe
(CompositeSubscription helps)
And don’t include references to the
object/activity
MADRID · NOV 27-28 · 2015
Easy to unsubscribe
@Override
protected void onStop() {
super.onStop();
subscription.unsubscribe();
}
.isUnsubscribed() :(
MADRID · NOV 27-28 · 2015
Let’s recap
MADRID · NOV 27-28 · 2015
a library
to represent any operation as an
asynchronous data stream
on any thread,
declaratively composed,
and consumed by multiple objects
MADRID · NOV 27-28 · 2015
a library
to represent any operation as an
observable
on any thread,
declaratively composed,
and consumed by multiple objects
MADRID · NOV 27-28 · 2015
a library
to represent any operation as an
observable
with schedulers
declaratively composed,
and consumed by multiple objects
MADRID · NOV 27-28 · 2015
a library
to represent any operation as an
observable
with schedulers
and operators
and consumed by multiple objects
MADRID · NOV 27-28 · 2015
a library
to represent any operation as an
observable
with schedulers
and operators
listened by subscribers
MADRID · NOV 27-28 · 2015
But...
MADRID · NOV 27-28 · 2015
But...
● Learning curve
● Hard to debug (Frodo library)
● Backpressure
MADRID · NOV 27-28 · 2015
Questions?
MADRID · NOV 27-28 · 2015
Where to know more...
● reactivex.io (amazing docs)
● RxJava wiki
● Dan Lew
● Use cases
MADRID · NOV 27-28 · 2015
Where to know more...
nhpatt (twitter | github | email | slack)
I’ll do anything for good votes
MADRID · NOV 27-28 · 2015
Feedback
Click here :P
MADRID · NOV 27-28 · 2015
RxJava in practice
Javier Gamarra
MADRID · NOV 27-28 · 2015
Other interesting operators...
MADRID · NOV 27-28 · 2015
Take
service.listRepos("nhpatt")
.flatMap(Observable::from)
.map(Repo::getName)
.map((s) -> s.replace("-", " "))
.filter((s) -> s.startsWith("Android"))
.take(2)
.subscribe(System.out::println);
MADRID · NOV 27-28 · 2015
Operators
distinctUntilChanged
compose
MADRID · NOV 27-28 · 2015
Errors?
MADRID · NOV 27-28 · 2015
onError() is called if an Exception is thrown at
any time (this is cool)
The operators don't have to handle the
Exception
No more callbacks
Errors
MADRID · NOV 27-28 · 2015
Errors
And we can customize the flow:
onErrorResumeNext
onErrorReturn
retry
...
MADRID · NOV 27-28 · 2015
Why this is useful?
MADRID · NOV 27-28 · 2015
Why this is useful?
Observables and subscribers can do
anything
MADRID · NOV 27-28 · 2015
Why this is useful?
Observable a database query
Subscriber displaying results on the screen
MADRID · NOV 27-28 · 2015
Why this is useful?
Observable a click on the screen
Subscriber reacting to it
MADRID · NOV 27-28 · 2015
Why this is useful?
Observable a stream of bytes from the
internet
Subscriber write them to disk
MADRID · NOV 27-28 · 2015
Why this is useful?
Observable and Subscriber are independent
of the transformations
MADRID · NOV 27-28 · 2015
Why this is useful?
I can compose/chain any map/filter calls I
want
Only matters the return type
MADRID · NOV 27-28 · 2015
Side effects?
MADRID · NOV 27-28 · 2015
Side effects
doOn methods:
● doOnNext() for debugging
● doOnError() for error handling
● doOnNext() to save/cache results
MADRID · NOV 27-28 · 2015
Side effects
Observable someObservable = Observable
.from(Arrays.asList(new Integer[]{2, 7, 11}))
.doOnNext(System.out::println)
.filter(prime -> prime % 2 == 0)
.doOnNext(System.out::println)
.count()
.doOnNext(System.out::println)
.map(
number -> String.format(“Contains %d
elements”, number)
);
MADRID · NOV 27-28 · 2015
Side effects
flatMap(id -> service.get()
.doOnError(t -> {
// report problem to UI
})
.onErrorResumeNext(Observable.empty()))
MADRID · NOV 27-28 · 2015
Cold & Hot
MADRID · NOV 27-28 · 2015
Cold & Hot
Observables only emit when someone
listening?
Cold observables only emit when subscribed
But hot observables emit instantly
MADRID · NOV 27-28 · 2015
Cold & Hot
You can convert between both states
● “Hot -> cold” using defer() or merge(),
zip()...
● “Cold -> Hot” using publish() & connect()
MADRID · NOV 27-28 · 2015
Cold & Hot
publish & connect?
“like transactions”
Assume everything is cold
MADRID · NOV 27-28 · 2015
Testing?
MADRID · NOV 27-28 · 2015
More cool things?
● testscheduler
● toIterator()
● Obs.error(), Obs.empty()
MADRID · NOV 27-28 · 2015
Subjects
MADRID · NOV 27-28 · 2015
Subjects
Both observable & observer
MADRID · NOV 27-28 · 2015
Subjects
AsyncSubject -> takeLast(1)
PublishSubject -> publish()
ReplaySubject -> replay()/cache()
BehaviorSubject -> replay(1)/cache(1)
MADRID · NOV 27-28 · 2015
RxJava in practice
Javier Gamarra

More Related Content

What's hot

Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 

What's hot (20)

RxJava Applied
RxJava AppliedRxJava Applied
RxJava Applied
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Introduction to Reactive Java
Introduction to Reactive JavaIntroduction to Reactive Java
Introduction to Reactive Java
 
rx-java-presentation
rx-java-presentationrx-java-presentation
rx-java-presentation
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
 
A dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenarioA dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenario
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 

Viewers also liked

Viewers also liked (9)

Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
 
RxBinding-kotlin
RxBinding-kotlinRxBinding-kotlin
RxBinding-kotlin
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
 
Kotlinにお触り
Kotlinにお触りKotlinにお触り
Kotlinにお触り
 
Introduction to Retrofit and RxJava
Introduction to Retrofit and RxJavaIntroduction to Retrofit and RxJava
Introduction to Retrofit and RxJava
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
RxJava - introduction & design
RxJava - introduction & designRxJava - introduction & design
RxJava - introduction & design
 
RxJava+RxAndroid (Lecture 20 – rx java)
RxJava+RxAndroid (Lecture 20 – rx java)RxJava+RxAndroid (Lecture 20 – rx java)
RxJava+RxAndroid (Lecture 20 – rx java)
 

Similar to RxJava in practice

VictoriaMetrics 15/12 Meet Up: 2022 Features Highlights
VictoriaMetrics 15/12 Meet Up: 2022 Features HighlightsVictoriaMetrics 15/12 Meet Up: 2022 Features Highlights
VictoriaMetrics 15/12 Meet Up: 2022 Features Highlights
VictoriaMetrics
 

Similar to RxJava in practice (20)

Codemotion 2015 - Akka voló sobre el nido del future
Codemotion 2015 - Akka voló sobre el nido del futureCodemotion 2015 - Akka voló sobre el nido del future
Codemotion 2015 - Akka voló sobre el nido del future
 
Codemotion akka voló sobre el nido del future
Codemotion   akka voló sobre el nido del futureCodemotion   akka voló sobre el nido del future
Codemotion akka voló sobre el nido del future
 
Introduction to spark
Introduction to sparkIntroduction to spark
Introduction to spark
 
Adding Realtime to your Projects
Adding Realtime to your ProjectsAdding Realtime to your Projects
Adding Realtime to your Projects
 
Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and Reagent
 
Realtime video streaming the open source way
Realtime video streaming the open source wayRealtime video streaming the open source way
Realtime video streaming the open source way
 
Cassandra for impatients
Cassandra for impatientsCassandra for impatients
Cassandra for impatients
 
QVT Traceability: What does it really mean?
QVT Traceability: What does it really mean?QVT Traceability: What does it really mean?
QVT Traceability: What does it really mean?
 
IoT with Ruby/mruby - RubyWorld Conference 2015
IoT with Ruby/mruby - RubyWorld Conference 2015IoT with Ruby/mruby - RubyWorld Conference 2015
IoT with Ruby/mruby - RubyWorld Conference 2015
 
VictoriaMetrics 15/12 Meet Up: 2022 Features Highlights
VictoriaMetrics 15/12 Meet Up: 2022 Features HighlightsVictoriaMetrics 15/12 Meet Up: 2022 Features Highlights
VictoriaMetrics 15/12 Meet Up: 2022 Features Highlights
 
Hello Java 8
Hello Java 8Hello Java 8
Hello Java 8
 
Functional reactive-talk 20170301-001
Functional reactive-talk 20170301-001Functional reactive-talk 20170301-001
Functional reactive-talk 20170301-001
 
OpenTSDB 2.0
OpenTSDB 2.0OpenTSDB 2.0
OpenTSDB 2.0
 
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
 
R workshop xx -- Parallel Computing with R
R workshop xx -- Parallel Computing with R R workshop xx -- Parallel Computing with R
R workshop xx -- Parallel Computing with R
 
2020 03-26 - meet up - zparkio
2020 03-26 - meet up - zparkio2020 03-26 - meet up - zparkio
2020 03-26 - meet up - zparkio
 
InfluxDB 101 – Concepts and Architecture by Michael DeSa, Software Engineer |...
InfluxDB 101 – Concepts and Architecture by Michael DeSa, Software Engineer |...InfluxDB 101 – Concepts and Architecture by Michael DeSa, Software Engineer |...
InfluxDB 101 – Concepts and Architecture by Michael DeSa, Software Engineer |...
 
GlusterD - Daemon refactoring
GlusterD - Daemon refactoringGlusterD - Daemon refactoring
GlusterD - Daemon refactoring
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
 
Functional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for MaintainabilityFunctional Programming in Java - Code for Maintainability
Functional Programming in Java - Code for Maintainability
 

More from Javier Gamarra

More from Javier Gamarra (14)

Performance myths in android
Performance myths in androidPerformance myths in android
Performance myths in android
 
Cambiar una empresa con juegos ágiles
Cambiar una empresa con juegos ágilesCambiar una empresa con juegos ágiles
Cambiar una empresa con juegos ágiles
 
New Android Languages
New Android LanguagesNew Android Languages
New Android Languages
 
5 meses de juegos ágiles
5 meses de juegos ágiles5 meses de juegos ágiles
5 meses de juegos ágiles
 
Opinionated android
Opinionated androidOpinionated android
Opinionated android
 
Arduino - Cuarta sesión
Arduino - Cuarta sesiónArduino - Cuarta sesión
Arduino - Cuarta sesión
 
Arduino - Tercera sesión
Arduino - Tercera sesiónArduino - Tercera sesión
Arduino - Tercera sesión
 
Hibernate - JPA @luce 5
Hibernate - JPA @luce 5Hibernate - JPA @luce 5
Hibernate - JPA @luce 5
 
Hibernate - JPA @luce 4
Hibernate - JPA @luce 4Hibernate - JPA @luce 4
Hibernate - JPA @luce 4
 
Hibernate - JPA @luce 3
Hibernate - JPA @luce 3Hibernate - JPA @luce 3
Hibernate - JPA @luce 3
 
Hibernate - JPA @luce 2
Hibernate - JPA @luce 2Hibernate - JPA @luce 2
Hibernate - JPA @luce 2
 
Hibernate - JPA @luce
Hibernate - JPA @luceHibernate - JPA @luce
Hibernate - JPA @luce
 
Codemotion 2013
Codemotion 2013Codemotion 2013
Codemotion 2013
 
CAS 2013
CAS 2013CAS 2013
CAS 2013
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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
 
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)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
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...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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...
 
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?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

RxJava in practice

  • 1. MADRID · NOV 27-28 · 2015 RxJava in practice Javier Gamarra
  • 2. MADRID · NOV 27-28 · 2015 http://kcy.me/29crj (slides) & http://kcy.me/296bu (commits)
  • 3. MADRID · NOV 27-28 · 2015 Environment Eclipse | Android Studio (RxAndroid) RxJava.jar [Java 8] || [Retrolambda] :P
  • 4. MADRID · NOV 27-28 · 2015 Environment Android Studio: compile 'io.reactivex:rxandroid:1.0.1' compile 'io.reactivex:rxjava:1.0.16' Eclipse: ● Copy jars to lib/ and add jar in project
  • 5. MADRID · NOV 27-28 · 2015 Github ● http://kcy.me/296bu ● koans ● código ● commit a commit ● Podéis preguntarme en cualquier momento
  • 6. MADRID · NOV 27-28 · 2015 Who? Javier Gamarra / @nhpatt @liferay @cyliconvalley / @agilespain
  • 7. MADRID · NOV 27-28 · 2015 Ask! Please? Pretty please? Please pretty please with sugar on top?
  • 8. MADRID · NOV 27-28 · 2015 Background?
  • 9. MADRID · NOV 27-28 · 2015 Why?
  • 10. MADRID · NOV 27-28 · 2015 Why? (in java) multithreading is hard futures are complicated callbacks are hell
  • 11. MADRID · NOV 27-28 · 2015 Rx comes to the rescue!
  • 12. MADRID · NOV 27-28 · 2015 a library to represent any operation as an asynchronous data stream on any thread, declaratively composed, and consumed by multiple objects
  • 13. MADRID · NOV 27-28 · 2015 a library
  • 14. MADRID · NOV 27-28 · 2015 A library? Extensions to .NET framework Netflix
  • 15. MADRID · NOV 27-28 · 2015 Libraries are tools If all you have is a hammer, everything looks like a nail
  • 16. MADRID · NOV 27-28 · 2015 a library to model Observables & Subscribers
  • 17. MADRID · NOV 27-28 · 2015 Observables and Subscribers An Observable emits items. A Subscriber consumes those items.
  • 18. MADRID · NOV 27-28 · 2015 Observer pattern?
  • 19. MADRID · NOV 27-28 · 2015 My very first observable Observable<String> myObs = Observable. create(new Observable. OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { subscriber.onNext( "Hi!"); subscriber.onCompleted(); } });
  • 20. MADRID · NOV 27-28 · 2015 My very first subscriber Subscriber<String> mySubs = new Subscriber<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable throwable) { } @Override public void onNext(String s) { System. out.println(s); } };
  • 21. MADRID · NOV 27-28 · 2015 My very first subscription myObs.subscribe(mySubs);
  • 22. MADRID · NOV 27-28 · 2015 A bit verbose... Let’s simplify with Java8 and RxJava ● lamdbas ● Observable.just ● .subscribe()
  • 23. MADRID · NOV 27-28 · 2015 That’s better... Observable .just("Hi!") .subscribe(System.out::println);
  • 24. MADRID · NOV 27-28 · 2015 Why? More than the observer pattern ● Observables only emit when someone listening ● OnFinished ● OnError
  • 25. MADRID · NOV 27-28 · 2015 Let’s use those differences subscribe admits 3 parameters ● OnNext ● OnFinished ● OnError
  • 26. MADRID · NOV 27-28 · 2015 You said “items” Observable.from admits a list of elements
  • 27. MADRID · NOV 27-28 · 2015 Ok, let’s recap… Iterators?
  • 28. MADRID · NOV 27-28 · 2015 Iterators? ● Iterators are pull and synchronous ● Subscribers are push and asynchronous
  • 29. MADRID · NOV 27-28 · 2015 to represent any operation as an “asynchronous data stream”
  • 30. MADRID · NOV 27-28 · 2015 Everything is a stream
  • 31. MADRID · NOV 27-28 · 2015 Everything is a stream We can model everything as a stream
  • 32. MADRID · NOV 27-28 · 2015 Everything is a stream A network call is also a stream Like using retrofit with this API
  • 33. MADRID · NOV 27-28 · 2015 “declaratively composed”
  • 34. MADRID · NOV 27-28 · 2015 Operators
  • 35. MADRID · NOV 27-28 · 2015 Operators Transform a stream rxmarbles and android app
  • 36. MADRID · NOV 27-28 · 2015 Operators Map
  • 37. MADRID · NOV 27-28 · 2015 Map List<String> severalThings = Arrays.asList("1", "2"); Observable.from(severalThings) .map((s) -> “Element “ + s) .subscribe(System.out::println);
  • 38. MADRID · NOV 27-28 · 2015 Map We can return another type: List<String> severalThings = Arrays.asList("1", "2"); Observable.from(severalThings) .map(Integer::valueOf) .subscribe(System.out::println);
  • 39. MADRID · NOV 27-28 · 2015 Map Let’s do the same with our repos… And… I can’t because we return a List And using Observable.from… NOP
  • 40. MADRID · NOV 27-28 · 2015 Flatmap Flatmap Obs -> elements
  • 41. MADRID · NOV 27-28 · 2015 Flatmap service.listRepos("nhpatt") .flatMap(Observable::from) .map(Repo::getName) .map((s) -> s.replace("-", " ")) .subscribe(System.out::println);
  • 42. MADRID · NOV 27-28 · 2015 Flatmap Concatmap -> ordered flatmap
  • 43. MADRID · NOV 27-28 · 2015 Filter service.listRepos("nhpatt") .flatMap(Observable::from) .map(Repo::getName) .map((s) -> s.replace("-", " ")) .filter((s) -> s.startsWith("Android")) .subscribe(System.out::println);
  • 44. MADRID · NOV 27-28 · 2015 Scan & old code service.listRepos("nhpatt") .flatMap(Observable::from) .map(Repo::getName) .map((s) -> s.replace("-", " ")) .filter((s) -> s.startsWith("Android")) .take(2) .map(String::length) .scan((x, y) -> x * y) .subscribe(System.out::println);
  • 45. MADRID · NOV 27-28 · 2015 Scan & old code (l) -> { int result = 0; int i = 0; int oldLength = 1; for (Repo repo : l) { String name = repo.getName(); String replacedName = name.replace( "-", " "); if (replacedName.startsWith( "Android") && i < 2) { result = replacedName.length() * oldLength; oldLength = result; System.out.println(result); i++; } } return result;
  • 46. MADRID · NOV 27-28 · 2015 Operators ● merge ● flatMap ● zip Nice things™ : parallel jobs!
  • 47. MADRID · NOV 27-28 · 2015 Zipping requests Observable<Repo> repo = service.listRepos("nhpatt") .flatMap(Observable::from) .take(1); Observable<Commit> commit = service.listCommits("nhpatt", "Android") .flatMap(Observable::from) .take(1); Observable.zip(repo, commit, this::updateCommit).subscribe (repo1 -> { System.out.println(repo1.getCommit().getUrl()); });
  • 48. MADRID · NOV 27-28 · 2015 Operators Amazing documentation ● Async ● Blocking ● Combining ● Conditional ● Error handling ● Filtering ● Mathematical ● Creation ● String ● Transforming ● Utility
  • 49. MADRID · NOV 27-28 · 2015 Subscribers are asynchronous? No, not really
  • 50. MADRID · NOV 27-28 · 2015 “on any thread”
  • 51. MADRID · NOV 27-28 · 2015 Schedulers!
  • 52. MADRID · NOV 27-28 · 2015 Schedulers I define an API declaratively and later in the implementation run it: asynchronously or in a separate Thread or in a Threadpool or synchronously ...
  • 53. MADRID · NOV 27-28 · 2015 Schedulers .subscribeOn(Schedulers...) .observeOn(Schedulers...) ● io ● computation ● newThread ● trampoline ● test
  • 54. MADRID · NOV 27-28 · 2015 Schedulers service.listRepos("nhpatt") .subscribeOn(Schedulers.immediate()) .observeOn(Schedulers.immediate()) .subscribe(System.out::println);
  • 55. MADRID · NOV 27-28 · 2015 Schedulers RxJava operators have default threads Interval?
  • 56. MADRID · NOV 27-28 · 2015 Use cases?
  • 57. MADRID · NOV 27-28 · 2015 Use cases ● Autocomplete with debounce | sample… ● Accumulate calls with buffer... ● Polling with timeout | window… ● Form Validation with combineLatest… ● Retrieve data fast from cache | network call with concat | merge… ● Button click with delay, listen on other thread
  • 58. MADRID · NOV 27-28 · 2015 Android?
  • 59. MADRID · NOV 27-28 · 2015 Why?
  • 60. MADRID · NOV 27-28 · 2015 Why? (in android) Main/UI thread and background problem ● Can’t do heavy tasks on UI ● Can’t update view on background ● AsyncTasks are bad ● Handlers can leak
  • 61. MADRID · NOV 27-28 · 2015 How RxAndroid helps?
  • 62. MADRID · NOV 27-28 · 2015 Android schedulers service.listRepos("nhpatt") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(newRepos -> { repos.addAll(newRepos); adapter.notifyDataSetChanged(); });
  • 63. MADRID · NOV 27-28 · 2015 Orientation Problem Orientation Problem ● onCreate gets called again ● state is lost
  • 64. MADRID · NOV 27-28 · 2015 Orientation Problem Programmer’s job: ● Store/Restore state ● Restore view ● Call again the user task? ● Wait until it finishes?
  • 65. MADRID · NOV 27-28 · 2015 How RxAndroid helps?
  • 66. MADRID · NOV 27-28 · 2015 Orientation Problem Observable is easy to persist (retain | singleton) Observable can continue (cache and retry) RxLifecycle
  • 67. MADRID · NOV 27-28 · 2015 Orientation Problem Observable<List<Repo>> github = RetrofitService. getGithub() .listRepos("nhpatt") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .cache();
  • 68. MADRID · NOV 27-28 · 2015 More Android Lifecycle (RxLifecyle) Views (RxBinding)
  • 69. MADRID · NOV 27-28 · 2015 But...
  • 70. MADRID · NOV 27-28 · 2015 But... Subscriptions leak memory :’( We have to call to unsubscribe (CompositeSubscription helps) And don’t include references to the object/activity
  • 71. MADRID · NOV 27-28 · 2015 Easy to unsubscribe @Override protected void onStop() { super.onStop(); subscription.unsubscribe(); } .isUnsubscribed() :(
  • 72. MADRID · NOV 27-28 · 2015 Let’s recap
  • 73. MADRID · NOV 27-28 · 2015 a library to represent any operation as an asynchronous data stream on any thread, declaratively composed, and consumed by multiple objects
  • 74. MADRID · NOV 27-28 · 2015 a library to represent any operation as an observable on any thread, declaratively composed, and consumed by multiple objects
  • 75. MADRID · NOV 27-28 · 2015 a library to represent any operation as an observable with schedulers declaratively composed, and consumed by multiple objects
  • 76. MADRID · NOV 27-28 · 2015 a library to represent any operation as an observable with schedulers and operators and consumed by multiple objects
  • 77. MADRID · NOV 27-28 · 2015 a library to represent any operation as an observable with schedulers and operators listened by subscribers
  • 78. MADRID · NOV 27-28 · 2015 But...
  • 79. MADRID · NOV 27-28 · 2015 But... ● Learning curve ● Hard to debug (Frodo library) ● Backpressure
  • 80. MADRID · NOV 27-28 · 2015 Questions?
  • 81. MADRID · NOV 27-28 · 2015 Where to know more... ● reactivex.io (amazing docs) ● RxJava wiki ● Dan Lew ● Use cases
  • 82. MADRID · NOV 27-28 · 2015 Where to know more... nhpatt (twitter | github | email | slack) I’ll do anything for good votes
  • 83. MADRID · NOV 27-28 · 2015 Feedback Click here :P
  • 84. MADRID · NOV 27-28 · 2015 RxJava in practice Javier Gamarra
  • 85. MADRID · NOV 27-28 · 2015 Other interesting operators...
  • 86. MADRID · NOV 27-28 · 2015 Take service.listRepos("nhpatt") .flatMap(Observable::from) .map(Repo::getName) .map((s) -> s.replace("-", " ")) .filter((s) -> s.startsWith("Android")) .take(2) .subscribe(System.out::println);
  • 87. MADRID · NOV 27-28 · 2015 Operators distinctUntilChanged compose
  • 88. MADRID · NOV 27-28 · 2015 Errors?
  • 89. MADRID · NOV 27-28 · 2015 onError() is called if an Exception is thrown at any time (this is cool) The operators don't have to handle the Exception No more callbacks Errors
  • 90. MADRID · NOV 27-28 · 2015 Errors And we can customize the flow: onErrorResumeNext onErrorReturn retry ...
  • 91. MADRID · NOV 27-28 · 2015 Why this is useful?
  • 92. MADRID · NOV 27-28 · 2015 Why this is useful? Observables and subscribers can do anything
  • 93. MADRID · NOV 27-28 · 2015 Why this is useful? Observable a database query Subscriber displaying results on the screen
  • 94. MADRID · NOV 27-28 · 2015 Why this is useful? Observable a click on the screen Subscriber reacting to it
  • 95. MADRID · NOV 27-28 · 2015 Why this is useful? Observable a stream of bytes from the internet Subscriber write them to disk
  • 96. MADRID · NOV 27-28 · 2015 Why this is useful? Observable and Subscriber are independent of the transformations
  • 97. MADRID · NOV 27-28 · 2015 Why this is useful? I can compose/chain any map/filter calls I want Only matters the return type
  • 98. MADRID · NOV 27-28 · 2015 Side effects?
  • 99. MADRID · NOV 27-28 · 2015 Side effects doOn methods: ● doOnNext() for debugging ● doOnError() for error handling ● doOnNext() to save/cache results
  • 100. MADRID · NOV 27-28 · 2015 Side effects Observable someObservable = Observable .from(Arrays.asList(new Integer[]{2, 7, 11})) .doOnNext(System.out::println) .filter(prime -> prime % 2 == 0) .doOnNext(System.out::println) .count() .doOnNext(System.out::println) .map( number -> String.format(“Contains %d elements”, number) );
  • 101. MADRID · NOV 27-28 · 2015 Side effects flatMap(id -> service.get() .doOnError(t -> { // report problem to UI }) .onErrorResumeNext(Observable.empty()))
  • 102. MADRID · NOV 27-28 · 2015 Cold & Hot
  • 103. MADRID · NOV 27-28 · 2015 Cold & Hot Observables only emit when someone listening? Cold observables only emit when subscribed But hot observables emit instantly
  • 104. MADRID · NOV 27-28 · 2015 Cold & Hot You can convert between both states ● “Hot -> cold” using defer() or merge(), zip()... ● “Cold -> Hot” using publish() & connect()
  • 105. MADRID · NOV 27-28 · 2015 Cold & Hot publish & connect? “like transactions” Assume everything is cold
  • 106. MADRID · NOV 27-28 · 2015 Testing?
  • 107. MADRID · NOV 27-28 · 2015 More cool things? ● testscheduler ● toIterator() ● Obs.error(), Obs.empty()
  • 108. MADRID · NOV 27-28 · 2015 Subjects
  • 109. MADRID · NOV 27-28 · 2015 Subjects Both observable & observer
  • 110. MADRID · NOV 27-28 · 2015 Subjects AsyncSubject -> takeLast(1) PublishSubject -> publish() ReplaySubject -> replay()/cache() BehaviorSubject -> replay(1)/cache(1)
  • 111. MADRID · NOV 27-28 · 2015 RxJava in practice Javier Gamarra