SlideShare a Scribd company logo
Reactive Functional
Programming with Java 8
on Android N
Shipeng Xu
May 6th 2016
What is Reactive
Programming?
Observer Pattern
An Observable emits items.
A Subscriber consumes those items.
(from RxJava in practice)
Observable Subscriber
Items
Observable & Subscriber
Observable Transform
Items
Subscriber
Observable & Subscriber
Why Reactive
Programming?
Quick example
• Find all png images under a folder
• Load the images into a gallery view
http://gank.io/post/560e15be2dca930e00da1083
new Thread() {
@Override
public void run() {
super.run();
for (Folder folder : folders) {
File[] files = folder.listFiles();
for (File file : files) {
if (file.getName().endsWith(".png")) {
final Bitmap bitmap = getBitmapFromFile(file);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
imageCollectorView.addImage(bitmap);
}
});
}
}
}
}
}.start();
Vanilla Java
http://gank.io/post/560e15be2dca930e00da1083
Observable.from(folders)
.flatMap((folder) -> Observable.from(folder.listFiles()) )
.filter((file) -> file.getName().endsWith(".png") )
.map((file) -> getBitmapFromFile(file) )
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((bitmap) -> imageCollectorView.addImage(bitmap) );
RxJava
Create an Observable
Observable observable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext("Hello");
subscriber.onNext("World");
subscriber.onCompleted();
}
});
observable.subscribe(subscriber);To subscribe to an observable:
Observable.just("Hello", "World")
Or the shorter version:
Subscriber<String> subscriber = new Subscriber<String>() {
@Override
public void onNext(String s) {
Log.d(tag, "Item: " + s);
}
@Override
public void onCompleted() {
Log.d(tag, "Completed!");
}
@Override
public void onError(Throwable e) {
Log.d(tag, "Error!");
}
};
Subscriber Sample
http://reactivex.io/documentation/observable.html
http://rxmarbles.com/
Reactive Functional Programming with Java 8 on Android N
Demo project
Get started with Java 8 on
Android N
android {
compileSdkVersion 'android-N'
buildToolsVersion "24.0.0 rc1"
defaultConfig {
applicationId "me.billhsu.rxdemo"
minSdkVersion 'N'
targetSdkVersion 'N'
versionCode 1
versionName "1.0"
jackOptions {
enabled true
}
}
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
}
Rx libraries for Android
RxAndroid - Provide a Scheduler that schedules on the main thread or
any given Looper.
RxLifecycle - Lifecycle handling APIs for Android apps using RxJava
RxBinding - RxJava binding APIs for Android's UI widgets.
SqlBrite - A lightweight wrapper around SQLiteOpenHelper and
ContentResolver which introduces reactive stream semantics to queries.
Android-ReactiveLocation - Library that wraps location play services
API boilerplate with a reactive friendly API.
rx-preferences - Reactive SharedPreferences for Android
RxFit - Reactive Fitness API Library for Android
RxWear - Reactive Wearable API Library for Android
RxPermissions - Android runtime permissions powered by RxJava
RxNotification - Easy way to register, remove and manage notifications
using RxJava
Android Scheduler
Schedulers.io()
Schedulers.computation()
Schedulers.newThread()
Schedulers.from(Executor)
Schedulers.immediate()
Schedulers.trampoline()
Observable.just("Hello", "World")
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(/* update UI*/);
REST Responses to
Observables
public interface GitHubApi {
@GET("users/{users}/followers")
Observable<List<GitHubUser>> getFollowers(@Path("users") String user);
@GET("users/{users}")
Observable<GitHubUser> getUser(@Path("users") String user);
}
private void setupRetrofit() {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(5, TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl("https://api.github.com/")
.build();
gitHubApi = retrofit.create(GitHubApi.class);
}
https://api.github.com/users/billhsu
RxView.clicks(button).subscribe((a) -> {
button.setClickable(false);
adapter.getGitHubUserList().clear();
adapter.notifyDataSetChanged();
progressBar.setVisibility(View.VISIBLE);
gitHubApi.getFollowers(userName.getText().toString())
.flatMapIterable(users -> users)
.flatMap(user -> gitHubApi.getUser(user.getLogin()))
.filter(user -> !TextUtils.isEmpty(user.getCompany()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
user -> {
adapter.getGitHubUserList().add(user);
adapter.notifyDataSetChanged();
},
error -> {
Toast.makeText(MainActivity.this, error.toString(),
Toast.LENGTH_LONG).show();
button.setClickable(true);
progressBar.setVisibility(View.GONE);
},
() -> {
button.setClickable(true);
progressBar.setVisibility(View.GONE);
});
});
The click stream
Click stream to GitHubUser
Stream
RxView.clicks(button).subscribe((a) -> {
button.setClickable(false);
adapter.getGitHubUserList().clear();
adapter.notifyDataSetChanged();
progressBar.setVisibility(View.VISIBLE);
gitHubApi.getFollowers(userName.getText().toString())
.flatMapIterable(users -> users)
.flatMap(user -> gitHubApi.getUser(user.getLogin()))
.filter(user -> !TextUtils.isEmpty(user.getCompany()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
user -> {
adapter.getGitHubUserList().add(user);
adapter.notifyDataSetChanged();
},
error -> {
Toast.makeText(MainActivity.this, error.toString(),
Toast.LENGTH_LONG).show();
button.setClickable(true);
progressBar.setVisibility(View.GONE);
},
() -> {
button.setClickable(true);
progressBar.setVisibility(View.GONE);
});
});
Subscribe to GitHubUser
Stream
RxView.clicks(button).subscribe((a) -> {
button.setClickable(false);
adapter.getGitHubUserList().clear();
adapter.notifyDataSetChanged();
progressBar.setVisibility(View.VISIBLE);
gitHubApi.getFollowers(userName.getText().toString())
.flatMapIterable(users -> users)
.flatMap(user -> gitHubApi.getUser(user.getLogin()))
.filter(user -> !TextUtils.isEmpty(user.getCompany()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
user -> {
adapter.getGitHubUserList().add(user);
adapter.notifyDataSetChanged();
},
error -> {
Toast.makeText(MainActivity.this, error.toString(),
Toast.LENGTH_LONG).show();
button.setClickable(true);
progressBar.setVisibility(View.GONE);
},
() -> {
button.setClickable(true);
progressBar.setVisibility(View.GONE);
});
});
Summary

More Related Content

What's hot (20)

An Introduction to RxJava
An Introduction to RxJava
Sanjay Acharya
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
Egor Andreevich
 
Reactive programming with RxJava
Reactive programming with RxJava
Jobaer Chowdhury
 
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Víctor Leonel Orozco López
 
Eclipse MicroProfile metrics: Practical use cases
Eclipse MicroProfile metrics: Practical use cases
Víctor Leonel Orozco López
 
Eclipse MicroProfile para el desarrollador ocupado
Eclipse MicroProfile para el desarrollador ocupado
Víctor Leonel Orozco López
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
GDG Korea
 
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Víctor Leonel Orozco López
 
RxJava on Android
RxJava on Android
Dustin Graham
 
Modern Android app library stack
Modern Android app library stack
Tomáš Kypta
 
Eclipse MicroProfile para o desenvolvedor ocupado
Eclipse MicroProfile para o desenvolvedor ocupado
Víctor Leonel Orozco López
 
Dropwizard
Dropwizard
Tetiana Saputo
 
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
Maarten Balliauw
 
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Toshiaki Maki
 
Rxjava meetup presentation
Rxjava meetup presentation
Guillaume Valverde
 
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
Maarten Balliauw
 
RxJava 2.0 介紹
RxJava 2.0 介紹
Kros Huang
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Airflow and supervisor
Airflow and supervisor
Rafael Roman Otero
 
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Maarten Balliauw
 
An Introduction to RxJava
An Introduction to RxJava
Sanjay Acharya
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
Egor Andreevich
 
Reactive programming with RxJava
Reactive programming with RxJava
Jobaer Chowdhury
 
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Víctor Leonel Orozco López
 
Eclipse MicroProfile para el desarrollador ocupado
Eclipse MicroProfile para el desarrollador ocupado
Víctor Leonel Orozco López
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
GDG Korea
 
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Víctor Leonel Orozco López
 
Modern Android app library stack
Modern Android app library stack
Tomáš Kypta
 
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
Maarten Balliauw
 
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Toshiaki Maki
 
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
Maarten Balliauw
 
RxJava 2.0 介紹
RxJava 2.0 介紹
Kros Huang
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Maarten Balliauw
 

Similar to Reactive Functional Programming with Java 8 on Android N (20)

Reactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary Grygleski
PolyglotMeetups
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
Fabio Collini
 
Practical RxJava for Android
Practical RxJava for Android
Tomáš Kypta
 
Petro Gordiievych "From Java 9 to Java 12"
Petro Gordiievych "From Java 9 to Java 12"
LogeekNightUkraine
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
Kros Huang
 
Overview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Reactive Microservice And Spring5
Reactive Microservice And Spring5
Jay Lee
 
React inter3
React inter3
Oswald Campesato
 
Spring 4-groovy
Spring 4-groovy
GR8Conf
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
Ali Muzaffar
 
Replication - Nick Carboni - ManageIQ Design Summit 2016
Replication - Nick Carboni - ManageIQ Design Summit 2016
ManageIQ
 
IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016
Trayan Iliev
 
Java SE 8 & EE 7 Launch
Java SE 8 & EE 7 Launch
Digicomp Academy AG
 
Reactive java programming for the impatient
Reactive java programming for the impatient
Grant Steinfeld
 
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Loiane Groner
 
Microservices and modularity with java
Microservices and modularity with java
DPC Consulting Ltd
 
soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch
 
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Loiane Groner
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
GuardSquare
 
Reactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary Grygleski
PolyglotMeetups
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
Fabio Collini
 
Practical RxJava for Android
Practical RxJava for Android
Tomáš Kypta
 
Petro Gordiievych "From Java 9 to Java 12"
Petro Gordiievych "From Java 9 to Java 12"
LogeekNightUkraine
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
Kros Huang
 
Overview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Reactive Microservice And Spring5
Reactive Microservice And Spring5
Jay Lee
 
Spring 4-groovy
Spring 4-groovy
GR8Conf
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
Ali Muzaffar
 
Replication - Nick Carboni - ManageIQ Design Summit 2016
Replication - Nick Carboni - ManageIQ Design Summit 2016
ManageIQ
 
IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016
Trayan Iliev
 
Reactive java programming for the impatient
Reactive java programming for the impatient
Grant Steinfeld
 
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Loiane Groner
 
Microservices and modularity with java
Microservices and modularity with java
DPC Consulting Ltd
 
soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch
 
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Loiane Groner
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
GuardSquare
 
Ad

Recently uploaded (20)

Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Ad

Reactive Functional Programming with Java 8 on Android N