SlideShare a Scribd company logo
Saving lives with RxJava
Shahar Barsheshet
About me
Shahar Barsheshet
shahar2k5
Talk agenda
● Intro to RxJava
● Why and How?
● Common Mistakes
and some tips
Do You Rx?
Intro to Rx
Wikipedia:
reactive programming is a programming paradigm oriented around data flows and the
propagation of change. This means that it should be possible to express static or
dynamic data flows with ease in the programming languages used, and that the
underlying execution model will automatically propagate changes through the data flow.
RxJava ← Reactive eXtentions ← Reactive Programing
Mmmm…. Data Flow….
Intro to Rx
Definition from ReactiveX:
ReactiveX is a library for composing asynchronous and event-based programs by using
observable sequences.
It extends the observer pattern to support sequences of data and/or events and adds
operators that allow you to compose sequences together declaratively while abstracting
away concerns about things like low-level threading, synchronization, thread-safety,
concurrent data structures, and non-blocking I/O.
The Problem
Concurrency
The Problem
Some solutions:
● AsyncTask
○ Comfortable - nice callbacks
○ Error handling sucks - Tuple??
○ The lost Context
○ Composing multiple calls… oh no!
○ Testing… yeah right…
● Threading
○ Very hard to handle concurrency
○ Bugs are easy to create
● IntentService
○ Easy to use
○ Updating the UI isn't trivial
○ Concurrency…???
The Solution
RxJava
● Can easily join background operations
● Easy error handling
● Can be tied to lifecycle
● Easy to test
● Remove boilerplate code
RxJava with Android
● RxAndroid - Android Schedulers
● RxBinding - by Jake Wharton
● RxJava
compile 'com.jakewharton.rxbinding:rxbinding:1.0.0'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.2.6'
compile 'io.reactivex:rxjava:1.2.6'
Rx Concepts
● Observable and the observer contracts
● Operators
● Schedulers
The Observable
Observables emits data when you subscribe to them.
● onNext(0 … ∞)
● onComplete(0 … 1)
● onError(0 … 1)
onError() and onComplete() are exclusive.
Subscribers and Subscriptions
Once subscribing to an Observable, we get the Subscription object.
The Subscription describes the connection between the Observable and the
observer.
As long as we are subscribed, we will get data emitted from the Observable.
To stop the Observable from emitting more item, we just need to call
subscription.unsubscribe();
Error handling
When an error occurs, the Observable stop emitting data.
onError(Throwable t) gets called so we can handle the error in a proper way.
What happens if we don't implement onError(Throwable t) ?
The Magazine...
Subscribing - creating the Subscription
Preparing dataData ready - user
can observe
Error!!!Complete
Observable
Observer
Unsubscribe
Subscribers and Subscriptions
Subscription mySubscription = myIntegers.subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
// YEY!! finished emitting all the integers
}
@Override
public void onError(Throwable e) {
// something bad happened
}
@Override
public void onNext(Integer integer) {
// we just got a new integer
}
});
Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5);
mySubscription.unsubscribe();
Operators
ReactiveX offers lots of operators to handle and manipulate data.
Creating Observables
● Just — convert an object or a set of objects into an Observable that emits that or those objects
● Interval — create an Observable that emits a sequence of integers spaced by a particular time interval
● Create — create an Observable from scratch by calling observer methods programmatically
Transforming Observables
● Map — transform the items emitted by an Observable by applying a function to each item
Combining Observables
● Merge — combine multiple Observables into one by merging their emissions
● CombineLatest — when an item is emitted by either of two Observables, combine the latest item emitted by each
Observable via a specified function and emit items based on the results of this function
Operators - Map
Operators - Filter
Operators
Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5);
Observable<Integer> evenIntegers = myIntegers.filter(new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer integer) {
return integer % 2 == 0;
}
});
mappedToString.subscribe();
// onNext("Just mapped 2")
// onNext("Just mapped 4")
// onComplete()
Observable<String> mappedToString = evenIntegers.map(new Func1<Integer, String>() {
@Override
public String call(Integer integer) {
return "Just mapped " + integer;
}
});
Operators
Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5);
myIntegers.filter(new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer integer) {
return integer % 2 == 0;
}
}).map(new Func1<Integer, String>() {
@Override
public String call(Integer integer) {
return "Just mapped " + integer;
}
});
Lambda Expression
new Func1<String, Integer>()
{
@Override
public Integer call(String string)
{
return string.length();
}
};
(String string) ->
{
return string.length();
};
string -> string.length();
= =
Operators
myIntegers
.filter(integer -> integer % 2 == 0)
.map(integer -> "Just mapped " + integer);
Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5);
myIntegers.filter(new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer integer) {
return integer % 2 == 0;
}
}).map(new Func1<Integer, String>() {
@Override
public String call(Integer integer) {
return "Just mapped " + integer;
}
});
From this:
To this:
Schedulers
By default, an Observable and the chain of operators that you apply to it
will do its work, and will notify its observers, on the same thread on
which its Subscribe method is called. The SubscribeOn operator
changes this behavior by specifying a different Scheduler on which the
Observable should operate.
● Schedulers.computation( ) meant for computational work such
as event-loops and callback processing
● Schedulers.io( ) meant for I/O-bound work such as asynchronous
performance of blocking I/O, this scheduler is backed by a
thread-pool that will grow as needed
● AndroidSchedulers.mainThread( ) (using RxAndroid)
subscribeOn() and observeOn
AsyncTask
String userId = "102";
AsyncTask getUserTask = new AsyncTask<String, Void, User>() {
@Override
protected User doInBackground(String[] strings) {
return ServerAPI.getUserProfile(strings[0]);
}
@Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
mAdapter.add(user.firstName + " " + user.lastName);
}
};
getUserTask.execute(userId);
AsyncTask
String userId = "102";
Observable.just(userId)
.map(id -> ServerAPI.getUserProfile(id))
.subscribe(user -> {
mAdapter.add(user.firstName + " " + user.lastName);
}, throwable -> {
Toast.makeText(this, "An error occurred, please try again"
, Toast.LENGTH_SHORT).show();
});
Observable.just(userId)
.map(id -> ServerAPI.getUserProfile(id))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(user -> {
mAdapter.add(user.firstName + " " + user.lastName);
}, throwable -> {
Toast.makeText(this, "An error occurred, please try again"
, Toast.LENGTH_SHORT).show();
});
TimerTask
//initialize the TimerTask's job
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
// Do some cool stuff
// on the UI Thread
}
};
//set a new Timer
Timer timer = new Timer();
//schedule the timer, after the first 5000ms
// the TimerTask will run every 10000ms
timer.schedule(timerTask, 5000, 10000);
TimerTask
Observable.interval(5000, 10000, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(interval -> {
// Do some cool stuff
// on the UI Thread
});
public static Observable<Long> interval(long initialDelay, long period, TimeUnit unit) {
return interval(initialDelay, period, unit, Schedulers.computation());
}
Search address using Google Places API
mEditText.addTextChangedListener(new
TextWatcher() {
@Override
public void beforeTextChanged(CharSequence
charSequence, int i, int i1, int i2) {
GetPlaces task = new GetPlaces();
String check = mEditText.getText().toString();
task.execute(check);
}
@Override
public void onTextChanged(CharSequence
charSequence, int i, int i1, int i2) {}
@Override
public void afterTextChanged(Editable editable) {}
});
// get the list of predictions in an asynctask
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... args) {
ArrayList<String> predictionsArr = new ArrayList<String>();
try {
ServerAPI.getSuggestionsFromGoogleAPI(args[0]);
} catch (Exception e) {
e.printStackTrace();
}
// return all the predictions based on the typing the in the search
return predictionsArr;
}
@Override
protected void onPostExecute(ArrayList<String> result) {
// update the list with new data
}
}
Search address using Google Places API - using RxJava
RxTextView.textChanges(mEditText)
.debounce(300, TimeUnit.MILLISECONDS)
.distinctUntilChanged()
.filter(charSequence -> charSequence != null && charSequence.length() > 0)
.map(charSequence -> ServerAPI.getSuggestionsFromGoogleAPI(charSequence))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(throwable -> {
// show user something about this error
})
.subscribe(strings -> {
// update the list with new data
});
Getting the current country
Network
Provider
IP
GPS
Getting the current country
public Observable<CountryProvider> getCountryCode()
{
Observable<CountryProvider> locationObservable = getCountryFromLocationProvider();
Observable<CountryProvider> ipObservable = getCountryFromNetwork();
Observable<CountryProvider> providerObservable = getCountryFromNetworkProvider();
return Observable.merge(providerObservable, locationObservable, ipObservable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.startWith(new CountryProvider("il", CountryProviderType.DEFAULT))
.scan((countryProvider, countryProvider2) -> {
if (countryProvider2 == null)
{
return countryProvider;
}
int value1 = countryProvider.getProviderType().getValue();
int value2 = countryProvider2.getProviderType().getValue();
return value1 > value2 ? countryProvider : countryProvider2;
})
.distinctUntilChanged()
.onErrorReturn(null);
}
Getting the current country
mCountryManager.getCountryCode()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(countryProvider ->
{
Toast.makeText(this, "Got country " + countryProvider.getCountryCode()
+ " from provider: " + countryProvider.getProviderType().name()
, Toast.LENGTH_LONG).show();
});
Common
Mistakes
And Tips
Default Schedulers
Observable.just("hello")
.subscribe(); → happens on the current thread
Observable.just("hello")
.delay(1000, TimeUnit.MILLISECONDS)
.subscribe(); → happens on the computation thread
VS
Multiple SubscribeOn
Observable.just("Hello")
.subscribeOn(Schedulers.io())
.map(string -> string.length())
.subscribeOn(Schedulers.computation())
.subscribe();
io()
ObserveOn
Observable.just("Hello") // current thread
.observeOn(Schedulers.io())
.map(string -> string.length()) // io
.observeOn(Schedulers.computation())
.subscribe(); // computation
Multiple observeOn do work as expected.
Memory leak
● Subscribers can leak!
● Use leakcanary
● Unsubscribe when leaving
Unsubscribe
Subscription subscription = Observable.just("Hello").subscribe();
subscription.unsubscribe();
CompositeSubscription
Subscription myIntegerSubscription = myIntegers.subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {}
@Override
public void onNext(Integer integer) {}
});
Subscription myStringSubscription = myStrings.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {}
@Override
public void onNext(String string) {}
});
compositeSubscription.add(myIntegerSubscription);
compositeSubscription.add(myStringSubscription);
Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5);
Observable<String> myStrings = Observable.just("one", "two", "three", "four", "five");
compositeSubscription.unsubscribe();
// OR
compositeSubscription.clear();
CompositeSubscription compositeSubscription = new CompositeSubscription();
LifeCycle
private CompositeSubscription mSubscriptions;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mSubscriptions = new CompositeSubscription();
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (!mSubscriptions.isUnsubscribed())
mSubscriptions.unsubscribe();
}
public void addSubscriptionToViewLifeCycle(Subscription subscription) {
mSubscriptions.add(subscription);
}
Thanks!
By the way
We are hiring!Shahar Barsheshet
Source code

More Related Content

What's hot

Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no Android
Guilherme Branco
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3Dillon Lee
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
Mario Fusco
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Nexus FrontierTech
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NET
EPAM
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on Android
Guilherme Branco
 
Apache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API BasicsApache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API Basics
Flink Forward
 
Art of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityArt of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code quality
Dmytro Patserkovskyi
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
GDG Korea
 
Microsoft word java
Microsoft word   javaMicrosoft word   java
Microsoft word java
Ravi Purohit
 
Testing in android
Testing in androidTesting in android
Testing in android
jtrindade
 
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
Netesh Kumar
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
Designveloper
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
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
Constantine Mars
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
Bartosz Sypytkowski
 
Showdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp KrennShowdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp Krenn
JavaDayUA
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
Bartosz Sypytkowski
 

What's hot (20)

Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no Android
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
 
Reactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NETReactive Extensions: classic Observer in .NET
Reactive Extensions: classic Observer in .NET
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on Android
 
Apache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API BasicsApache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API Basics
 
Art of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code qualityArt of unit testing: How developer should care about code quality
Art of unit testing: How developer should care about code quality
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 
Microsoft word java
Microsoft word   javaMicrosoft word   java
Microsoft word java
 
Testing in android
Testing in androidTesting in android
Testing in android
 
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
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Call Back
Call BackCall Back
Call Back
 
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
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
Showdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp KrennShowdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp Krenn
 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
 

Viewers also liked

Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Model-View-ViewModel and RxJava
Model-View-ViewModel and RxJavaModel-View-ViewModel and RxJava
Model-View-ViewModel and RxJava
Florina Muntenescu
 
Rx-Java - Como compor sua aplicacao com Observables
Rx-Java - Como compor sua aplicacao com ObservablesRx-Java - Como compor sua aplicacao com Observables
Rx-Java - Como compor sua aplicacao com Observables
lokimad
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
Kros Huang
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
Tomáš Kypta
 
wilfor grancolombia
wilfor grancolombiawilfor grancolombia
wilfor grancolombia
wilformarentes1986
 
Calc Flur
Calc FlurCalc Flur
Calc Flur
Amit Karkare
 
Facebook-oglasavanje-prezentacija
Facebook-oglasavanje-prezentacijaFacebook-oglasavanje-prezentacija
Facebook-oglasavanje-prezentacijaMilan Vasovic
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
4. introducción al diseño de politicas ambientales
4. introducción al diseño de politicas ambientales4. introducción al diseño de politicas ambientales
4. introducción al diseño de politicas ambientales
Leonardo Lenin Banegas Barahona
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
Frank Lyaruu
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
Arjun Sridhar U R
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
Arjun Sridhar U R
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
Pokequesthero
 
Core java online training
Core java online trainingCore java online training
Core java online training
Glory IT Technologies Pvt. Ltd.
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
Christopher Akinlade
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
yugandhar vadlamudi
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
Arjun Sridhar U R
 

Viewers also liked (20)

Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Model-View-ViewModel and RxJava
Model-View-ViewModel and RxJavaModel-View-ViewModel and RxJava
Model-View-ViewModel and RxJava
 
Rx-Java - Como compor sua aplicacao com Observables
Rx-Java - Como compor sua aplicacao com ObservablesRx-Java - Como compor sua aplicacao com Observables
Rx-Java - Como compor sua aplicacao com Observables
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
wilfor grancolombia
wilfor grancolombiawilfor grancolombia
wilfor grancolombia
 
Calc Flur
Calc FlurCalc Flur
Calc Flur
 
Facebook-oglasavanje-prezentacija
Facebook-oglasavanje-prezentacijaFacebook-oglasavanje-prezentacija
Facebook-oglasavanje-prezentacija
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
4. introducción al diseño de politicas ambientales
4. introducción al diseño de politicas ambientales4. introducción al diseño de politicas ambientales
4. introducción al diseño de politicas ambientales
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
 

Similar to Saving lives with rx java

2 презентация rx java+android
2 презентация rx java+android2 презентация rx java+android
2 презентация rx java+android
STEP Computer Academy (Zaporozhye)
 
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
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
Thinh Thanh
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
YarikS
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
Pavan Chitumalla
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
Dustin Graham
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
JollyRogers5
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
Tomáš Kypta
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
bloodredsun
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
Maxim Volgin
 
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje CrnjakJavantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
Tomasz Kowalczewski
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
Tomasz Kowalczewski
 
Iniciación rx java
Iniciación rx javaIniciación rx java
Iniciación rx java
Elisa De Gregorio Medrano
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
Outware Mobile
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
Sandeep Joshi
 
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
Rx 101  - Tamir Dresher - Copenhagen .NET User GroupRx 101  - Tamir Dresher - Copenhagen .NET User Group
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
Tamir Dresher
 

Similar to Saving lives with rx java (20)

2 презентация rx java+android
2 презентация rx java+android2 презентация rx java+android
2 презентация rx java+android
 
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
 
RxAndroid
RxAndroidRxAndroid
RxAndroid
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje CrnjakJavantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
Javantura v3 - Going Reactive with RxJava – Hrvoje Crnjak
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Iniciación rx java
Iniciación rx javaIniciación rx java
Iniciación rx java
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
Rx 101  - Tamir Dresher - Copenhagen .NET User GroupRx 101  - Tamir Dresher - Copenhagen .NET User Group
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
 

Recently uploaded

TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 

Recently uploaded (20)

TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 

Saving lives with rx java

  • 1. Saving lives with RxJava Shahar Barsheshet
  • 3. Talk agenda ● Intro to RxJava ● Why and How? ● Common Mistakes and some tips
  • 5. Intro to Rx Wikipedia: reactive programming is a programming paradigm oriented around data flows and the propagation of change. This means that it should be possible to express static or dynamic data flows with ease in the programming languages used, and that the underlying execution model will automatically propagate changes through the data flow. RxJava ← Reactive eXtentions ← Reactive Programing
  • 7. Intro to Rx Definition from ReactiveX: ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences. It extends the observer pattern to support sequences of data and/or events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O.
  • 9. The Problem Some solutions: ● AsyncTask ○ Comfortable - nice callbacks ○ Error handling sucks - Tuple?? ○ The lost Context ○ Composing multiple calls… oh no! ○ Testing… yeah right… ● Threading ○ Very hard to handle concurrency ○ Bugs are easy to create ● IntentService ○ Easy to use ○ Updating the UI isn't trivial ○ Concurrency…???
  • 10. The Solution RxJava ● Can easily join background operations ● Easy error handling ● Can be tied to lifecycle ● Easy to test ● Remove boilerplate code
  • 11. RxJava with Android ● RxAndroid - Android Schedulers ● RxBinding - by Jake Wharton ● RxJava compile 'com.jakewharton.rxbinding:rxbinding:1.0.0' compile 'io.reactivex:rxandroid:1.2.1' compile 'io.reactivex:rxjava:1.2.6' compile 'io.reactivex:rxjava:1.2.6'
  • 12. Rx Concepts ● Observable and the observer contracts ● Operators ● Schedulers
  • 13. The Observable Observables emits data when you subscribe to them. ● onNext(0 … ∞) ● onComplete(0 … 1) ● onError(0 … 1) onError() and onComplete() are exclusive.
  • 14. Subscribers and Subscriptions Once subscribing to an Observable, we get the Subscription object. The Subscription describes the connection between the Observable and the observer. As long as we are subscribed, we will get data emitted from the Observable. To stop the Observable from emitting more item, we just need to call subscription.unsubscribe();
  • 15. Error handling When an error occurs, the Observable stop emitting data. onError(Throwable t) gets called so we can handle the error in a proper way. What happens if we don't implement onError(Throwable t) ?
  • 16. The Magazine... Subscribing - creating the Subscription Preparing dataData ready - user can observe Error!!!Complete Observable Observer Unsubscribe
  • 17. Subscribers and Subscriptions Subscription mySubscription = myIntegers.subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { // YEY!! finished emitting all the integers } @Override public void onError(Throwable e) { // something bad happened } @Override public void onNext(Integer integer) { // we just got a new integer } }); Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5); mySubscription.unsubscribe();
  • 18. Operators ReactiveX offers lots of operators to handle and manipulate data. Creating Observables ● Just — convert an object or a set of objects into an Observable that emits that or those objects ● Interval — create an Observable that emits a sequence of integers spaced by a particular time interval ● Create — create an Observable from scratch by calling observer methods programmatically Transforming Observables ● Map — transform the items emitted by an Observable by applying a function to each item Combining Observables ● Merge — combine multiple Observables into one by merging their emissions ● CombineLatest — when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function
  • 21. Operators Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5); Observable<Integer> evenIntegers = myIntegers.filter(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { return integer % 2 == 0; } }); mappedToString.subscribe(); // onNext("Just mapped 2") // onNext("Just mapped 4") // onComplete() Observable<String> mappedToString = evenIntegers.map(new Func1<Integer, String>() { @Override public String call(Integer integer) { return "Just mapped " + integer; } });
  • 22. Operators Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5); myIntegers.filter(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { return integer % 2 == 0; } }).map(new Func1<Integer, String>() { @Override public String call(Integer integer) { return "Just mapped " + integer; } });
  • 23. Lambda Expression new Func1<String, Integer>() { @Override public Integer call(String string) { return string.length(); } }; (String string) -> { return string.length(); }; string -> string.length(); = =
  • 24. Operators myIntegers .filter(integer -> integer % 2 == 0) .map(integer -> "Just mapped " + integer); Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5); myIntegers.filter(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { return integer % 2 == 0; } }).map(new Func1<Integer, String>() { @Override public String call(Integer integer) { return "Just mapped " + integer; } }); From this: To this:
  • 25. Schedulers By default, an Observable and the chain of operators that you apply to it will do its work, and will notify its observers, on the same thread on which its Subscribe method is called. The SubscribeOn operator changes this behavior by specifying a different Scheduler on which the Observable should operate. ● Schedulers.computation( ) meant for computational work such as event-loops and callback processing ● Schedulers.io( ) meant for I/O-bound work such as asynchronous performance of blocking I/O, this scheduler is backed by a thread-pool that will grow as needed ● AndroidSchedulers.mainThread( ) (using RxAndroid) subscribeOn() and observeOn
  • 26. AsyncTask String userId = "102"; AsyncTask getUserTask = new AsyncTask<String, Void, User>() { @Override protected User doInBackground(String[] strings) { return ServerAPI.getUserProfile(strings[0]); } @Override protected void onPostExecute(User user) { super.onPostExecute(user); mAdapter.add(user.firstName + " " + user.lastName); } }; getUserTask.execute(userId);
  • 27. AsyncTask String userId = "102"; Observable.just(userId) .map(id -> ServerAPI.getUserProfile(id)) .subscribe(user -> { mAdapter.add(user.firstName + " " + user.lastName); }, throwable -> { Toast.makeText(this, "An error occurred, please try again" , Toast.LENGTH_SHORT).show(); }); Observable.just(userId) .map(id -> ServerAPI.getUserProfile(id)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(user -> { mAdapter.add(user.firstName + " " + user.lastName); }, throwable -> { Toast.makeText(this, "An error occurred, please try again" , Toast.LENGTH_SHORT).show(); });
  • 28. TimerTask //initialize the TimerTask's job TimerTask timerTask = new TimerTask() { @Override public void run() { // Do some cool stuff // on the UI Thread } }; //set a new Timer Timer timer = new Timer(); //schedule the timer, after the first 5000ms // the TimerTask will run every 10000ms timer.schedule(timerTask, 5000, 10000);
  • 29. TimerTask Observable.interval(5000, 10000, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(interval -> { // Do some cool stuff // on the UI Thread }); public static Observable<Long> interval(long initialDelay, long period, TimeUnit unit) { return interval(initialDelay, period, unit, Schedulers.computation()); }
  • 30. Search address using Google Places API mEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { GetPlaces task = new GetPlaces(); String check = mEditText.getText().toString(); task.execute(check); } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void afterTextChanged(Editable editable) {} }); // get the list of predictions in an asynctask class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> { @Override protected ArrayList<String> doInBackground(String... args) { ArrayList<String> predictionsArr = new ArrayList<String>(); try { ServerAPI.getSuggestionsFromGoogleAPI(args[0]); } catch (Exception e) { e.printStackTrace(); } // return all the predictions based on the typing the in the search return predictionsArr; } @Override protected void onPostExecute(ArrayList<String> result) { // update the list with new data } }
  • 31. Search address using Google Places API - using RxJava RxTextView.textChanges(mEditText) .debounce(300, TimeUnit.MILLISECONDS) .distinctUntilChanged() .filter(charSequence -> charSequence != null && charSequence.length() > 0) .map(charSequence -> ServerAPI.getSuggestionsFromGoogleAPI(charSequence)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(throwable -> { // show user something about this error }) .subscribe(strings -> { // update the list with new data });
  • 32. Getting the current country Network Provider IP GPS
  • 33. Getting the current country public Observable<CountryProvider> getCountryCode() { Observable<CountryProvider> locationObservable = getCountryFromLocationProvider(); Observable<CountryProvider> ipObservable = getCountryFromNetwork(); Observable<CountryProvider> providerObservable = getCountryFromNetworkProvider(); return Observable.merge(providerObservable, locationObservable, ipObservable) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .startWith(new CountryProvider("il", CountryProviderType.DEFAULT)) .scan((countryProvider, countryProvider2) -> { if (countryProvider2 == null) { return countryProvider; } int value1 = countryProvider.getProviderType().getValue(); int value2 = countryProvider2.getProviderType().getValue(); return value1 > value2 ? countryProvider : countryProvider2; }) .distinctUntilChanged() .onErrorReturn(null); }
  • 34. Getting the current country mCountryManager.getCountryCode() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(countryProvider -> { Toast.makeText(this, "Got country " + countryProvider.getCountryCode() + " from provider: " + countryProvider.getProviderType().name() , Toast.LENGTH_LONG).show(); });
  • 36. Default Schedulers Observable.just("hello") .subscribe(); → happens on the current thread Observable.just("hello") .delay(1000, TimeUnit.MILLISECONDS) .subscribe(); → happens on the computation thread VS
  • 37. Multiple SubscribeOn Observable.just("Hello") .subscribeOn(Schedulers.io()) .map(string -> string.length()) .subscribeOn(Schedulers.computation()) .subscribe(); io()
  • 38. ObserveOn Observable.just("Hello") // current thread .observeOn(Schedulers.io()) .map(string -> string.length()) // io .observeOn(Schedulers.computation()) .subscribe(); // computation Multiple observeOn do work as expected.
  • 39. Memory leak ● Subscribers can leak! ● Use leakcanary ● Unsubscribe when leaving
  • 40. Unsubscribe Subscription subscription = Observable.just("Hello").subscribe(); subscription.unsubscribe();
  • 41. CompositeSubscription Subscription myIntegerSubscription = myIntegers.subscribe(new Subscriber<Integer>() { @Override public void onCompleted() {} @Override public void onError(Throwable e) {} @Override public void onNext(Integer integer) {} }); Subscription myStringSubscription = myStrings.subscribe(new Subscriber<String>() { @Override public void onCompleted() {} @Override public void onError(Throwable e) {} @Override public void onNext(String string) {} }); compositeSubscription.add(myIntegerSubscription); compositeSubscription.add(myStringSubscription); Observable<Integer> myIntegers = Observable.just(1, 2, 3, 4, 5); Observable<String> myStrings = Observable.just("one", "two", "three", "four", "five"); compositeSubscription.unsubscribe(); // OR compositeSubscription.clear(); CompositeSubscription compositeSubscription = new CompositeSubscription();
  • 42. LifeCycle private CompositeSubscription mSubscriptions; @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mSubscriptions = new CompositeSubscription(); } @Override public void onDestroyView() { super.onDestroyView(); if (!mSubscriptions.isUnsubscribed()) mSubscriptions.unsubscribe(); } public void addSubscriptionToViewLifeCycle(Subscription subscription) { mSubscriptions.add(subscription); }
  • 43. Thanks! By the way We are hiring!Shahar Barsheshet Source code