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)

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

PPTX
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
PPTX
Introduction to RxJava on Android
Chris Arriola
 
PDF
RxJava@DAUG
Maxim Volgin
 
PPTX
Reactive Programming on Android - RxAndroid - RxJava
Ali Muzaffar
 
PDF
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
PDF
RxJava@Android
Maxim Volgin
 
PDF
RxJava pour Android : présentation lors du GDG Android Montréal
Sidereo
 
PPTX
Reactive programming with rx java
CongTrung Vnit
 
PDF
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft
 
PPTX
Reactive programming with RxAndroid
Savvycom Savvycom
 
PPTX
Rxandroid
Thinh Thanh
 
PPTX
RxAndroid
Thinh Thanh
 
PDF
RxJava - introduction & design
allegro.tech
 
PPTX
RxJava2 Slides
YarikS
 
PPTX
RxJava 2 Reactive extensions for the JVM
Netesh Kumar
 
PPTX
Reactive Programming on Android
Guilherme Branco
 
PDF
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Codemotion
 
PDF
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
PPTX
Introduction to Reactive programming
Dwi Randy Herdinanto
 
PDF
Saving lives with rx java
Shahar Barsheshet
 
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
Introduction to RxJava on Android
Chris Arriola
 
RxJava@DAUG
Maxim Volgin
 
Reactive Programming on Android - RxAndroid - RxJava
Ali Muzaffar
 
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
RxJava@Android
Maxim Volgin
 
RxJava pour Android : présentation lors du GDG Android Montréal
Sidereo
 
Reactive programming with rx java
CongTrung Vnit
 
Sperasoft Talks: RxJava Functional Reactive Programming on Android
Sperasoft
 
Reactive programming with RxAndroid
Savvycom Savvycom
 
Rxandroid
Thinh Thanh
 
RxAndroid
Thinh Thanh
 
RxJava - introduction & design
allegro.tech
 
RxJava2 Slides
YarikS
 
RxJava 2 Reactive extensions for the JVM
Netesh Kumar
 
Reactive Programming on Android
Guilherme Branco
 
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Codemotion
 
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
Introduction to Reactive programming
Dwi Randy Herdinanto
 
Saving lives with rx java
Shahar Barsheshet
 
Ad

Recently uploaded (20)

PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Ad

Reactive Functional Programming with Java 8 on Android N