SlideShare ist ein Scribd-Unternehmen logo
1 von 54
Downloaden Sie, um offline zu lesen
@fernando_cejas
http://www.fernandocejas.com
The Mayans Lost Guide
To RxJava on Android
@fernando_cejas
Curious learner
Meet...
Android lover
Software engineer
Geek
#Reactive
1- of, relating to, or marked by reaction or
reactance.
2- readily responsive to a stimulus.
RxJava is a Java VM implementation
of Reactive X (Reactive Extensions): ˝
a library for composing asynchronous
and event-based programs by using
observable sequences.
What is RxJava?
Why should
we go
reactive?
Multithreading is always complex˝
Concurrency˝
Java Futures are Expensive to Compose˝
Java Futures˝
Callbacks Have Their Own Problems˝
Callbacks˝
@benjchristensen from @netflix
public class FuturesA {
public static void run() throws Exception {
ExecutorService executor =
new ThreadPoolExecutor(4, 4, 1,
TimeUnit.MINUTES,
new LinkedBlockingQueue<Runnable>());
Future<String> f1 = executor.submit(new CallToRemoteServiceA());
Future<String> f2 = executor.submit(new CallToRemoteServiceB());
System.out.println(f1.get() + " - " + f2.get());
}
}
https://gist.github.com/benjchristensen/4670979
#Java Futures
#Java Futures
https://gist.github.com/benjchristensen/4671081
public static void run() throws Exception {
ExecutorService executor =
new ThreadPoolExecutor(4, 4, 1,
TimeUnit.MINUTES,
new LinkedBlockingQueue<Runnable>());
try {
// get f3 with dependent result from f1
Future<String> f1 = executor.submit(new CallToRemoteServiceA());
Future<String> f3 = executor.submit(new CallToRemoteServiceC(f1.get()));
/* The work below can not proceed until f1.get()
completes even though there is no dependency */
// also get f4/f5 after dependency f2 completes
Future<Integer> f2 = executor.submit(new CallToRemoteServiceB());
Future<Integer> f4 = executor.submit(new CallToRemoteServiceD(f2.get()));
Future<Integer> f5 = executor.submit(new CallToRemoteServiceE(f2.get()));
System.out.println(f3.get() + " => " + (f4.get() * f5.get()));
} finally {
executor.shutdownNow();
}
}
#Java Futures
https://gist.github.com/benjchristensen/4671081
public static void run4() throws Exception {
ExecutorService executor =
new ThreadPoolExecutor(4, 4, 1,
TimeUnit.MINUTES,
new LinkedBlockingQueue<Runnable>());
try {
List<Future<?>> futures = new ArrayList<Future<?>>();
// kick off several async tasks
futures.add(executor.submit(new CallToRemoteServiceA()));
futures.add(executor.submit(new CallToRemoteServiceB()));
futures.add(executor.submit(new CallToRemoteServiceC("A")));
futures.add(executor.submit(new CallToRemoteServiceC("B")));
futures.add(executor.submit(new CallToRemoteServiceD(1)));
futures.add(executor.submit(new CallToRemoteServiceE(2)));
futures.add(executor.submit(new CallToRemoteServiceE(3)));
// as each completes do further work
for (Future<?> f : futures) {
/* this blocks so even if other futures in the list
complete earlier they will wait until this one is done */
doMoreWork(f.get());
}
} finally {
executor.shutdownNow();
}
}
Multithreading is always complex˝
Concurrency˝
Java Futures are Expensive to Compose˝
Java Futures˝
Callbacks Have Their Own Problems˝
Callbacks˝
@benjchristensen from @netflix
#Callbacks
https://gist.github.com/benjchristensen/4677544
...
// get f3 with dependent result from f1
executor.execute(new CallToRemoteServiceA(new Callback<String>() {
@Override
public void call(String f1) {
executor.execute(new CallToRemoteServiceC(new Callback<String>() {
@Override
public void call(String f3) {
// we have f1 and f3 now need to compose with others
System.out.println("intermediate callback: " + f3 + " => " + ("f4 * f5"));
// set to thread-safe variable accessible by external scope
f3Value.set(f3);
latch.countDown();
}
}, f1));
}
}));
...
Observables
Subscribers
Subscriptions
Schedulers
Operators
#RxJava Guys:
Observables
The Observable object is who
does the job.
Represents an object that sends
notifications (Provider) to a
Subscriptor (Observer).
Observables
Add 2 missing semantics to the
Observer pattern:
#1: Emits a signal to the consumer
when there is no more data available.
#2: Emits a signal to the consumer
when an error has occurred.
Observables
Observables
Subscribers
Subscribers provides a
mechanism for receiving push-
based notifications from
Observables, and permits
manual unsubscribing from
these Observables.
Subscribers
Not an observer pattern:
Observables often don't
start emitting items until
someone explicitly
subscribes to them.
Subscribers
Observables often don't
start emitting items until
someone explicitly
subscribes to them.
Subscribers
public class DefaultSubscriber<T> extends rx.Subscriber<T> {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
}
@Override public void onNext(T t) {
}
}
Subscriptions
Subscriptions represents the link
between your Observable and
your Subscriber.
#1: Subscriptions
#2: CompositeSubscriptions
#1: Schedulers.io()
#2: Schedulers.computation()
#3: Schedulers.from()
Schedulers
If you want to introduce multithreading into
your cascade of Observable operators, you
can do so by instructing those operators (or
particular Observables) to operate on
particular Schedulers.
Operators
Operators can be used in
between the source Observable
and the ultimate Subscriber to
manipulate emitted items.
You can even write your own
custom operators.
map()
Transform the items emitted by an Observable
by applying a function to each item.
flatMap()
Transforms the items emitted by an
Observable into Observables, then flatten the
emissions from those into a single Observable
(no order)
concatMap()
Transforms the items emitted by an
Observable into Observables, then flatten the
emissions from those into a single Observable
(keeps order)
flatMap() vs concatMap()
http://fernandocejas.com/2015/01/11/rxjava-observable-tranformation-concatmap-vs-flatmap/
filter()
Emits the same item it received, but only if it
passes the boolean check (predicate).
take()
Emit only the first n items emitted by an
Observable
doOnNext()
Allows us to add extra behavior each time an
item is emitted.
onError() is called if an
exception is thrown at any time.
Error handling
The operators do not have to
handle the exception.
onErrorResumeNext()
Instructs an Observable to emit a sequence of items if it
encounters an error.
onErrorReturn()
Instructs an Observable to emit a particular item when it
encounters an error.
onExceptionResumeNext()
Instructs an Observable to continue emitting items after it
encounters an exception.
retry()
If a source Observable emits an error, resubscribe to it in the
hopes that it will complete without error.
retryWhen()
If a source Observable emits an error, pass that error to another
Observable to determine whether to resubscribe to the source.
Error handling Operators
#1: Observable and Subscriber can do
anything
#2: The Observable and Subscriber are
independent of the transformational
steps in between them.
#3: Operators let you do anything to the
stream of data.
Key ideas behind RxJava
http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/
#1: Learning curve
#2: Too many anonymous classes
generated (OutOfMemory?)
#3: Verbosity (retrolambda to the
rescue?)
But there are some pitfalls…
#Example: Clean Architecture
#Example: Clean Architecture
@PerActivity
public class UserListPresenter extends DefaultSubscriber<List<User>>
implements Presenter {
private UserListView viewListView;
private final UseCase getUserListUseCase;
@Inject
public UserListPresenter(@Named("userList") UseCase getUserListUserCase,
UserModelDataMapper userModelDataMapper) {
this.getUserListUseCase = getUserListUserCase;
}
@Override public void destroy() {
this.getUserListUseCase.unsubscribe();
}
private void getUserList() {
this.getUserListUseCase.execute(this);
}
...
}
#Example: Reactive Presenter
#Example: Reactive Presenter
@PerActivity
public class UserListPresenter extends DefaultSubscriber<List<User>>
implements Presenter {
...
@Override public void onCompleted() {
this.hideViewLoading();
}
@Override public void onError(Throwable e) {
this.hideViewLoading();
this.showErrorMessage(new DefaultErrorBundle((Exception) e));
this.showViewRetry();
}
@Override public void onNext(List<User> users) {
this.showUsersCollectionInView(users);
}
}
#Example: Clean Architecture
#Example: UseCase
public abstract class UseCase {
private final ThreadExecutor threadExecutor;
private final PostExecutionThread postExecutionThread;
private Subscription subscription = Subscriptions.empty();
protected UseCase(ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) {
this.threadExecutor = threadExecutor;
this.postExecutionThread = postExecutionThread;
}
protected abstract Observable buildUseCaseObservable();
public void execute(Subscriber UseCaseSubscriber) {
this.subscription = this.buildUseCaseObservable()
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.getScheduler())
.subscribe(UseCaseSubscriber);
}
public void unsubscribe() {
if (!subscription.isUnsubscribed()) subscription.unsubscribe();
}
}
#Example: Execution Thread
/**
* MainThread (UI Thread) implementation based on a
* {@link rx.Scheduler} which will execute actions on
* the Android UI thread
*/
@Singleton
public class UIThread implements PostExecutionThread {
@Inject
public UIThread() {}
@Override public Scheduler getScheduler() {
return AndroidSchedulers.mainThread();
}
}
#Example: UseCase
/**
* This class is an implementation of {@link UseCase} that represents a
* use case for retrieving a collection of all {@link User}.
*/
public class GetUserListUseCase extends UseCase {
private final UserRepository userRepository;
@Inject
public GetUserListUseCase(UserRepository userRepository,
ThreadExecutor threadExecutor,
PostExecutionThread postExecutionThread) {
super(threadExecutor, postExecutionThread);
this.userRepository = userRepository;
}
@Override public Observable buildUseCaseObservable() {
return this.userRepository.getUsers();
}
}
#Example: Clean Architecture
#Example: Operator and Action
public class CloudUserDataStore implements UserDataStore {
private final RestApi restApi;
private final UserCache userCache;
private final Action1<UserEntity> saveToCacheAction = new Action1<UserEntity>() {
@Override public void call(UserEntity userEntity) {
if (userEntity != null) {
CloudUserDataStore.this.userCache.put(userEntity);
}
}
};
public CloudUserDataStore(RestApi restApi, UserCache userCache) {
this.restApi = restApi;
this.userCache = userCache;
}
@Override public Observable<List<UserEntity>> getUserEntityList() {
return this.restApi.getUserEntityList();
}
@Override public Observable<UserEntity> getUserEntityDetails(final int userId) {
return this.restApi.getUserEntityById(userId).doOnNext(saveToCacheAction);
}
}
#Example: Data transformation
@Singleton
public class UserDataRepository implements UserRepository {
private final UserDataStoreFactory userDataStoreFactory;
private final UserEntityDataMapper userEntityDataMapper;
private final Func1<List<UserEntity>, List<User>> userListEntityMapper =
new Func1<List<UserEntity>, List<User>>() {
@Override public List<User> call(List<UserEntity> userEntities) {
return UserDataRepository.this.userEntityDataMapper.transform(userEntities);
}
};
private final Func1<UserEntity, User>
userDetailsEntityMapper = new Func1<UserEntity, User>() {
@Override public User call(UserEntity userEntity) {
return UserDataRepository.this.userEntityDataMapper.transform(userEntity);
}
};
@Override public Observable<List<User>> getUsers() {
final UserDataStore userDataStore = this.userDataStoreFactory.createCloudDataStore();
return userDataStore.getUserEntityList().map(userListEntityMapper);
}
}
#Example: Observable creation
@Override public Observable<List<UserEntity>> getUserEntityList() {
return Observable.create(new Observable.OnSubscribe<List<UserEntity>>() {
@Override public void call(Subscriber<? super List<UserEntity>> subscriber) {
if (isThereInternetConnection()) {
try {
String responseUserEntities = getUserEntitiesFromApi();
subscriber.onNext(userEntityJsonMapper.transformUserEntityCollection(
responseUserEntities));
subscriber.onCompleted();
} catch (Exception e) {
subscriber.onError(new NetworkConnectionException(e.getCause()));
}
} else {
subscriber.onError(new NetworkConnectionException());
}
}
});
}
#1: Good starting point to switch to Rx
Observables.
#2: No need to deal with threading an
synchronization.
#3: Very simple to wrap an http
connection in an Observable
How do I start with RxJava?
Rx at data level
#1: We can convert our events into Rx
Observables
How do I start with RxJava?
Rx at view level
Observable input = Observable.FromEventPattern(textView, "TextChanged")
.Select(_ => textbox.Text)
.Throttle(TimeSpan.FromSeconds(0.5))
.DistinctUntilChanged();
#1: You will return Rx Observables in
domain layer.
#2: Be careful with side effects (Rx
Schedulers other than UI Thread)
How do I start with RxJava?
Rx at domain level
#1: By default, RxJava is synchronous.
#2: onSubscribe() is executed separately
for every new subscriber.
#3: Subscriptions leak memory.
Tips and Tricks
#4: Read the official documentation
References
Reactive Programming on Android With RxJava
https://mttkay.github.io/blog/2013/08/25/functional-reactive-programming-on-android-with-rxjava/
Grokking RxJava
http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/
Reactive Programming in the Netflix API with RxJava
http://techblog.netflix.com/2013/02/rxjava-netflix-api.html
Rx for .NET and RxJava for Android
http://futurice.com/blog/tech-pick-of-the-week-rx-for-net-and-rxjava-for-android
https://github.com/android10/Android-CleanArchitecture
Official Documentation
https://github.com/ReactiveX/RxJava/wiki
https://github.com/android10/Android-ReactiveProgramming
?˝
Source: US Census Bureau
Questions
@fernando_cejas
http://soundcloud.com/jobs
Thanks!

Weitere ähnliche Inhalte

Was ist angesagt?

Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in JavaYakov Fain
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014Thomas Lockney
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaMike Nakhimovich
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJSMattia Occhiuto
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015Ben Lesh
 
Code craftsmanship saturdays second session
Code craftsmanship saturdays second sessionCode craftsmanship saturdays second session
Code craftsmanship saturdays second sessionJean Marcel Belmont
 
Annotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark ArtsAnnotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark ArtsJames Kirkbride
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actorsbloodredsun
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesHaim Yadid
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsKonrad Malawski
 
MVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixMVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixFlorina Muntenescu
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2Yakov Fain
 
Reactive Extensions for JavaScript
Reactive Extensions for JavaScriptReactive Extensions for JavaScript
Reactive Extensions for JavaScriptJim Wooley
 

Was ist angesagt? (20)

Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
 
Introduction to Reactive Java
Introduction to Reactive JavaIntroduction to Reactive Java
Introduction to Reactive Java
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
 
Code craftsmanship saturdays second session
Code craftsmanship saturdays second sessionCode craftsmanship saturdays second session
Code craftsmanship saturdays second session
 
React hooks
React hooksReact hooks
React hooks
 
Annotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark ArtsAnnotation Processing - Demystifying Java's Dark Arts
Annotation Processing - Demystifying Java's Dark Arts
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
MVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mixMVVM and RxJava – the perfect mix
MVVM and RxJava – the perfect mix
 
Reactive programming in Angular 2
Reactive programming in Angular 2Reactive programming in Angular 2
Reactive programming in Angular 2
 
Reactive Extensions for JavaScript
Reactive Extensions for JavaScriptReactive Extensions for JavaScript
Reactive Extensions for JavaScript
 

Andere mochten auch

Material Design for Old Schoolers
Material Design for Old SchoolersMaterial Design for Old Schoolers
Material Design for Old SchoolersFernando Cejas
 
RxJava for Android - GDG and DataArt
RxJava for Android - GDG and DataArtRxJava for Android - GDG and DataArt
RxJava for Android - GDG and DataArtConstantine Mars
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Androidyo_waka
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for androidEsa Firman
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaKros Huang
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Headless fragments in Android
Headless fragments in AndroidHeadless fragments in Android
Headless fragments in AndroidAli Muzaffar
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
A pattern language for microservices (#gluecon #gluecon2016)
A pattern language for microservices (#gluecon #gluecon2016)A pattern language for microservices (#gluecon #gluecon2016)
A pattern language for microservices (#gluecon #gluecon2016)Chris Richardson
 
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Chris Richardson
 

Andere mochten auch (12)

Material Design for Old Schoolers
Material Design for Old SchoolersMaterial Design for Old Schoolers
Material Design for Old Schoolers
 
2 презентация rx java+android
2 презентация rx java+android2 презентация rx java+android
2 презентация rx java+android
 
RxJava for Android - GDG and DataArt
RxJava for Android - GDG and DataArtRxJava for Android - GDG and DataArt
RxJava for Android - GDG and DataArt
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Headless fragments in Android
Headless fragments in AndroidHeadless fragments in Android
Headless fragments in Android
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
A pattern language for microservices (#gluecon #gluecon2016)
A pattern language for microservices (#gluecon #gluecon2016)A pattern language for microservices (#gluecon #gluecon2016)
A pattern language for microservices (#gluecon #gluecon2016)
 
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
 

Ähnlich wie The Mayans Lost Guide to RxJava on Android

Java util concurrent
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
 
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
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
From Java 6 to Java 7 reference
From Java 6 to Java 7 referenceFrom Java 6 to Java 7 reference
From Java 6 to Java 7 referenceGiacomo Veneri
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksWO Community
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lispelliando dias
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an IntroductionRoberto Casadei
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...PROIDEA
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and AkkaYung-Lin Ho
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
T2 reading 20101126
T2 reading 20101126T2 reading 20101126
T2 reading 20101126Go Tanaka
 

Ähnlich wie The Mayans Lost Guide to RxJava on Android (20)

Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
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
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
From Java 6 to Java 7 reference
From Java 6 to Java 7 referenceFrom Java 6 to Java 7 reference
From Java 6 to Java 7 reference
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
T2 reading 20101126
T2 reading 20101126T2 reading 20101126
T2 reading 20101126
 
Welcome to rx java2
Welcome to rx java2Welcome to rx java2
Welcome to rx java2
 

Mehr von Fernando Cejas

It is about philosophy: culture of a good programmer
It is about philosophy: culture of a good programmerIt is about philosophy: culture of a good programmer
It is about philosophy: culture of a good programmerFernando Cejas
 
How to Become the MacGyver of Android Custom Views
How to Become the MacGyver of Android Custom ViewsHow to Become the MacGyver of Android Custom Views
How to Become the MacGyver of Android Custom ViewsFernando Cejas
 
Android UX-UI Design for Fun and Profit
Android UX-UI Design for Fun and ProfitAndroid UX-UI Design for Fun and Profit
Android UX-UI Design for Fun and ProfitFernando Cejas
 
How ANDROID TESTING changed how we think about Death - Second Edition
How ANDROID TESTING changed how we think about Death - Second EditionHow ANDROID TESTING changed how we think about Death - Second Edition
How ANDROID TESTING changed how we think about Death - Second EditionFernando Cejas
 
How ANDROID TESTING changed how we think about Death
How ANDROID TESTING changed how we think about DeathHow ANDROID TESTING changed how we think about Death
How ANDROID TESTING changed how we think about DeathFernando Cejas
 
Dinosaurs and Androids: The Listview Evolution
Dinosaurs and Androids: The Listview EvolutionDinosaurs and Androids: The Listview Evolution
Dinosaurs and Androids: The Listview EvolutionFernando Cejas
 
Inside Android Testing
Inside Android TestingInside Android Testing
Inside Android TestingFernando Cejas
 
Webview: The fifth element
Webview: The fifth elementWebview: The fifth element
Webview: The fifth elementFernando Cejas
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design PatternsFernando Cejas
 
Android Cloud To Device Messaging
Android Cloud To Device MessagingAndroid Cloud To Device Messaging
Android Cloud To Device MessagingFernando Cejas
 
Android Quick Introduction
Android Quick IntroductionAndroid Quick Introduction
Android Quick IntroductionFernando Cejas
 
Desarrollo android almacenamiento de datos
Desarrollo android    almacenamiento de datosDesarrollo android    almacenamiento de datos
Desarrollo android almacenamiento de datosFernando Cejas
 
Android simple 2d Layout animation
Android simple 2d Layout animationAndroid simple 2d Layout animation
Android simple 2d Layout animationFernando Cejas
 

Mehr von Fernando Cejas (14)

It is about philosophy: culture of a good programmer
It is about philosophy: culture of a good programmerIt is about philosophy: culture of a good programmer
It is about philosophy: culture of a good programmer
 
How to Become the MacGyver of Android Custom Views
How to Become the MacGyver of Android Custom ViewsHow to Become the MacGyver of Android Custom Views
How to Become the MacGyver of Android Custom Views
 
Android UX-UI Design for Fun and Profit
Android UX-UI Design for Fun and ProfitAndroid UX-UI Design for Fun and Profit
Android UX-UI Design for Fun and Profit
 
How ANDROID TESTING changed how we think about Death - Second Edition
How ANDROID TESTING changed how we think about Death - Second EditionHow ANDROID TESTING changed how we think about Death - Second Edition
How ANDROID TESTING changed how we think about Death - Second Edition
 
How ANDROID TESTING changed how we think about Death
How ANDROID TESTING changed how we think about DeathHow ANDROID TESTING changed how we think about Death
How ANDROID TESTING changed how we think about Death
 
Dinosaurs and Androids: The Listview Evolution
Dinosaurs and Androids: The Listview EvolutionDinosaurs and Androids: The Listview Evolution
Dinosaurs and Androids: The Listview Evolution
 
Inside Android Testing
Inside Android TestingInside Android Testing
Inside Android Testing
 
Webview: The fifth element
Webview: The fifth elementWebview: The fifth element
Webview: The fifth element
 
Nfc on Android
Nfc on AndroidNfc on Android
Nfc on Android
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
Android Cloud To Device Messaging
Android Cloud To Device MessagingAndroid Cloud To Device Messaging
Android Cloud To Device Messaging
 
Android Quick Introduction
Android Quick IntroductionAndroid Quick Introduction
Android Quick Introduction
 
Desarrollo android almacenamiento de datos
Desarrollo android    almacenamiento de datosDesarrollo android    almacenamiento de datos
Desarrollo android almacenamiento de datos
 
Android simple 2d Layout animation
Android simple 2d Layout animationAndroid simple 2d Layout animation
Android simple 2d Layout animation
 

Kürzlich hochgeladen

CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 

Kürzlich hochgeladen (20)

CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 

The Mayans Lost Guide to RxJava on Android

  • 3.
  • 4. #Reactive 1- of, relating to, or marked by reaction or reactance. 2- readily responsive to a stimulus.
  • 5. RxJava is a Java VM implementation of Reactive X (Reactive Extensions): ˝ a library for composing asynchronous and event-based programs by using observable sequences. What is RxJava?
  • 7. Multithreading is always complex˝ Concurrency˝ Java Futures are Expensive to Compose˝ Java Futures˝ Callbacks Have Their Own Problems˝ Callbacks˝ @benjchristensen from @netflix
  • 8. public class FuturesA { public static void run() throws Exception { ExecutorService executor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()); Future<String> f1 = executor.submit(new CallToRemoteServiceA()); Future<String> f2 = executor.submit(new CallToRemoteServiceB()); System.out.println(f1.get() + " - " + f2.get()); } } https://gist.github.com/benjchristensen/4670979 #Java Futures
  • 9. #Java Futures https://gist.github.com/benjchristensen/4671081 public static void run() throws Exception { ExecutorService executor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()); try { // get f3 with dependent result from f1 Future<String> f1 = executor.submit(new CallToRemoteServiceA()); Future<String> f3 = executor.submit(new CallToRemoteServiceC(f1.get())); /* The work below can not proceed until f1.get() completes even though there is no dependency */ // also get f4/f5 after dependency f2 completes Future<Integer> f2 = executor.submit(new CallToRemoteServiceB()); Future<Integer> f4 = executor.submit(new CallToRemoteServiceD(f2.get())); Future<Integer> f5 = executor.submit(new CallToRemoteServiceE(f2.get())); System.out.println(f3.get() + " => " + (f4.get() * f5.get())); } finally { executor.shutdownNow(); } }
  • 10. #Java Futures https://gist.github.com/benjchristensen/4671081 public static void run4() throws Exception { ExecutorService executor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()); try { List<Future<?>> futures = new ArrayList<Future<?>>(); // kick off several async tasks futures.add(executor.submit(new CallToRemoteServiceA())); futures.add(executor.submit(new CallToRemoteServiceB())); futures.add(executor.submit(new CallToRemoteServiceC("A"))); futures.add(executor.submit(new CallToRemoteServiceC("B"))); futures.add(executor.submit(new CallToRemoteServiceD(1))); futures.add(executor.submit(new CallToRemoteServiceE(2))); futures.add(executor.submit(new CallToRemoteServiceE(3))); // as each completes do further work for (Future<?> f : futures) { /* this blocks so even if other futures in the list complete earlier they will wait until this one is done */ doMoreWork(f.get()); } } finally { executor.shutdownNow(); } }
  • 11. Multithreading is always complex˝ Concurrency˝ Java Futures are Expensive to Compose˝ Java Futures˝ Callbacks Have Their Own Problems˝ Callbacks˝ @benjchristensen from @netflix
  • 12. #Callbacks https://gist.github.com/benjchristensen/4677544 ... // get f3 with dependent result from f1 executor.execute(new CallToRemoteServiceA(new Callback<String>() { @Override public void call(String f1) { executor.execute(new CallToRemoteServiceC(new Callback<String>() { @Override public void call(String f3) { // we have f1 and f3 now need to compose with others System.out.println("intermediate callback: " + f3 + " => " + ("f4 * f5")); // set to thread-safe variable accessible by external scope f3Value.set(f3); latch.countDown(); } }, f1)); } })); ...
  • 14. Observables The Observable object is who does the job. Represents an object that sends notifications (Provider) to a Subscriptor (Observer).
  • 15. Observables Add 2 missing semantics to the Observer pattern: #1: Emits a signal to the consumer when there is no more data available. #2: Emits a signal to the consumer when an error has occurred.
  • 18. Subscribers Subscribers provides a mechanism for receiving push- based notifications from Observables, and permits manual unsubscribing from these Observables.
  • 19. Subscribers Not an observer pattern: Observables often don't start emitting items until someone explicitly subscribes to them.
  • 20. Subscribers Observables often don't start emitting items until someone explicitly subscribes to them.
  • 21. Subscribers public class DefaultSubscriber<T> extends rx.Subscriber<T> { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(T t) { } }
  • 22. Subscriptions Subscriptions represents the link between your Observable and your Subscriber. #1: Subscriptions #2: CompositeSubscriptions
  • 23. #1: Schedulers.io() #2: Schedulers.computation() #3: Schedulers.from() Schedulers If you want to introduce multithreading into your cascade of Observable operators, you can do so by instructing those operators (or particular Observables) to operate on particular Schedulers.
  • 24. Operators Operators can be used in between the source Observable and the ultimate Subscriber to manipulate emitted items. You can even write your own custom operators.
  • 25. map() Transform the items emitted by an Observable by applying a function to each item.
  • 26. flatMap() Transforms the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable (no order)
  • 27. concatMap() Transforms the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable (keeps order)
  • 29. filter() Emits the same item it received, but only if it passes the boolean check (predicate).
  • 30. take() Emit only the first n items emitted by an Observable
  • 31. doOnNext() Allows us to add extra behavior each time an item is emitted.
  • 32. onError() is called if an exception is thrown at any time. Error handling The operators do not have to handle the exception.
  • 33. onErrorResumeNext() Instructs an Observable to emit a sequence of items if it encounters an error. onErrorReturn() Instructs an Observable to emit a particular item when it encounters an error. onExceptionResumeNext() Instructs an Observable to continue emitting items after it encounters an exception. retry() If a source Observable emits an error, resubscribe to it in the hopes that it will complete without error. retryWhen() If a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source. Error handling Operators
  • 34. #1: Observable and Subscriber can do anything #2: The Observable and Subscriber are independent of the transformational steps in between them. #3: Operators let you do anything to the stream of data. Key ideas behind RxJava http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/
  • 35. #1: Learning curve #2: Too many anonymous classes generated (OutOfMemory?) #3: Verbosity (retrolambda to the rescue?) But there are some pitfalls…
  • 38. @PerActivity public class UserListPresenter extends DefaultSubscriber<List<User>> implements Presenter { private UserListView viewListView; private final UseCase getUserListUseCase; @Inject public UserListPresenter(@Named("userList") UseCase getUserListUserCase, UserModelDataMapper userModelDataMapper) { this.getUserListUseCase = getUserListUserCase; } @Override public void destroy() { this.getUserListUseCase.unsubscribe(); } private void getUserList() { this.getUserListUseCase.execute(this); } ... } #Example: Reactive Presenter
  • 39. #Example: Reactive Presenter @PerActivity public class UserListPresenter extends DefaultSubscriber<List<User>> implements Presenter { ... @Override public void onCompleted() { this.hideViewLoading(); } @Override public void onError(Throwable e) { this.hideViewLoading(); this.showErrorMessage(new DefaultErrorBundle((Exception) e)); this.showViewRetry(); } @Override public void onNext(List<User> users) { this.showUsersCollectionInView(users); } }
  • 41. #Example: UseCase public abstract class UseCase { private final ThreadExecutor threadExecutor; private final PostExecutionThread postExecutionThread; private Subscription subscription = Subscriptions.empty(); protected UseCase(ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) { this.threadExecutor = threadExecutor; this.postExecutionThread = postExecutionThread; } protected abstract Observable buildUseCaseObservable(); public void execute(Subscriber UseCaseSubscriber) { this.subscription = this.buildUseCaseObservable() .subscribeOn(Schedulers.from(threadExecutor)) .observeOn(postExecutionThread.getScheduler()) .subscribe(UseCaseSubscriber); } public void unsubscribe() { if (!subscription.isUnsubscribed()) subscription.unsubscribe(); } }
  • 42. #Example: Execution Thread /** * MainThread (UI Thread) implementation based on a * {@link rx.Scheduler} which will execute actions on * the Android UI thread */ @Singleton public class UIThread implements PostExecutionThread { @Inject public UIThread() {} @Override public Scheduler getScheduler() { return AndroidSchedulers.mainThread(); } }
  • 43. #Example: UseCase /** * This class is an implementation of {@link UseCase} that represents a * use case for retrieving a collection of all {@link User}. */ public class GetUserListUseCase extends UseCase { private final UserRepository userRepository; @Inject public GetUserListUseCase(UserRepository userRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) { super(threadExecutor, postExecutionThread); this.userRepository = userRepository; } @Override public Observable buildUseCaseObservable() { return this.userRepository.getUsers(); } }
  • 45. #Example: Operator and Action public class CloudUserDataStore implements UserDataStore { private final RestApi restApi; private final UserCache userCache; private final Action1<UserEntity> saveToCacheAction = new Action1<UserEntity>() { @Override public void call(UserEntity userEntity) { if (userEntity != null) { CloudUserDataStore.this.userCache.put(userEntity); } } }; public CloudUserDataStore(RestApi restApi, UserCache userCache) { this.restApi = restApi; this.userCache = userCache; } @Override public Observable<List<UserEntity>> getUserEntityList() { return this.restApi.getUserEntityList(); } @Override public Observable<UserEntity> getUserEntityDetails(final int userId) { return this.restApi.getUserEntityById(userId).doOnNext(saveToCacheAction); } }
  • 46. #Example: Data transformation @Singleton public class UserDataRepository implements UserRepository { private final UserDataStoreFactory userDataStoreFactory; private final UserEntityDataMapper userEntityDataMapper; private final Func1<List<UserEntity>, List<User>> userListEntityMapper = new Func1<List<UserEntity>, List<User>>() { @Override public List<User> call(List<UserEntity> userEntities) { return UserDataRepository.this.userEntityDataMapper.transform(userEntities); } }; private final Func1<UserEntity, User> userDetailsEntityMapper = new Func1<UserEntity, User>() { @Override public User call(UserEntity userEntity) { return UserDataRepository.this.userEntityDataMapper.transform(userEntity); } }; @Override public Observable<List<User>> getUsers() { final UserDataStore userDataStore = this.userDataStoreFactory.createCloudDataStore(); return userDataStore.getUserEntityList().map(userListEntityMapper); } }
  • 47. #Example: Observable creation @Override public Observable<List<UserEntity>> getUserEntityList() { return Observable.create(new Observable.OnSubscribe<List<UserEntity>>() { @Override public void call(Subscriber<? super List<UserEntity>> subscriber) { if (isThereInternetConnection()) { try { String responseUserEntities = getUserEntitiesFromApi(); subscriber.onNext(userEntityJsonMapper.transformUserEntityCollection( responseUserEntities)); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(new NetworkConnectionException(e.getCause())); } } else { subscriber.onError(new NetworkConnectionException()); } } }); }
  • 48. #1: Good starting point to switch to Rx Observables. #2: No need to deal with threading an synchronization. #3: Very simple to wrap an http connection in an Observable How do I start with RxJava? Rx at data level
  • 49. #1: We can convert our events into Rx Observables How do I start with RxJava? Rx at view level Observable input = Observable.FromEventPattern(textView, "TextChanged") .Select(_ => textbox.Text) .Throttle(TimeSpan.FromSeconds(0.5)) .DistinctUntilChanged();
  • 50. #1: You will return Rx Observables in domain layer. #2: Be careful with side effects (Rx Schedulers other than UI Thread) How do I start with RxJava? Rx at domain level
  • 51. #1: By default, RxJava is synchronous. #2: onSubscribe() is executed separately for every new subscriber. #3: Subscriptions leak memory. Tips and Tricks #4: Read the official documentation
  • 52. References Reactive Programming on Android With RxJava https://mttkay.github.io/blog/2013/08/25/functional-reactive-programming-on-android-with-rxjava/ Grokking RxJava http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/ Reactive Programming in the Netflix API with RxJava http://techblog.netflix.com/2013/02/rxjava-netflix-api.html Rx for .NET and RxJava for Android http://futurice.com/blog/tech-pick-of-the-week-rx-for-net-and-rxjava-for-android https://github.com/android10/Android-CleanArchitecture Official Documentation https://github.com/ReactiveX/RxJava/wiki https://github.com/android10/Android-ReactiveProgramming
  • 53. ?˝ Source: US Census Bureau Questions