SlideShare una empresa de Scribd logo
1 de 22
Descargar para leer sin conexión
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/
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

Más contenido relacionado

La actualidad más candente

An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJavaSanjay Acharya
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJavaJobaer Chowdhury
 
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem novaKotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem novaVíctor Leonel Orozco López
 
Eclipse MicroProfile para el desarrollador ocupado
Eclipse MicroProfile para el desarrollador ocupadoEclipse MicroProfile para el desarrollador ocupado
Eclipse MicroProfile para el desarrollador ocupadoVíctor Leonel Orozco López
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGDG 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 lenguajeKotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeVíctor Leonel Orozco López
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš 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...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_a1Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1Toshiaki 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 SearchNDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and SearchMaarten Balliauw
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹Kros Huang
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick 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...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
 

La actualidad más candente (20)

An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJava
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJava
 
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem novaKotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
 
Eclipse MicroProfile metrics: Practical use cases
Eclipse MicroProfile metrics: Practical use casesEclipse MicroProfile metrics: Practical use cases
Eclipse MicroProfile metrics: Practical use cases
 
Eclipse MicroProfile para el desarrollador ocupado
Eclipse MicroProfile para el desarrollador ocupadoEclipse MicroProfile para el desarrollador ocupado
Eclipse MicroProfile para el desarrollador ocupado
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 
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 lenguajeKotlin+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
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Eclipse MicroProfile para o desenvolvedor ocupado
Eclipse MicroProfile para o desenvolvedor ocupadoEclipse MicroProfile para o desenvolvedor ocupado
Eclipse MicroProfile para o desenvolvedor ocupado
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
CloudBurst 2019 - Indexing and searching NuGet.org with Azure Functions and S...
 
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
 
Rxjava meetup presentation
Rxjava meetup presentationRxjava meetup presentation
Rxjava meetup presentation
 
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 SearchNDC 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
 
RxJava 2.0 介紹
RxJava 2.0 介紹RxJava 2.0 介紹
RxJava 2.0 介紹
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Airflow and supervisor
Airflow and supervisorAirflow and supervisor
Airflow and supervisor
 
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
Indexing and searching NuGet.org with Azure Functions and Search - Cloud Deve...
 

Similar a Reactive Functional Programming with Java 8 on Android N

Reactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary GrygleskiReactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary GrygleskiPolyglotMeetups
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Fabio Collini
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Petro Gordiievych "From Java 9 to Java 12"
Petro Gordiievych "From Java 9 to Java 12"Petro Gordiievych "From Java 9 to Java 12"
Petro Gordiievych "From Java 9 to Java 12"LogeekNightUkraine
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaKros Huang
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Reactive Microservice And Spring5
Reactive Microservice And Spring5Reactive Microservice And Spring5
Reactive Microservice And Spring5Jay Lee
 
Spring 4-groovy
Spring 4-groovySpring 4-groovy
Spring 4-groovyGR8Conf
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
 
Replication - Nick Carboni - ManageIQ Design Summit 2016
Replication - Nick Carboni - ManageIQ Design Summit 2016Replication - Nick Carboni - ManageIQ Design Summit 2016
Replication - Nick Carboni - ManageIQ Design Summit 2016ManageIQ
 
IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016Trayan Iliev
 
Reactive java programming for the impatient
Reactive java programming for the impatientReactive java programming for the impatient
Reactive java programming for the impatientGrant Steinfeld
 
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConfFull-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConfLoiane Groner
 
Microservices and modularity with java
Microservices and modularity with javaMicroservices and modularity with java
Microservices and modularity with javaDPC Consulting Ltd
 
soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6soft-shake.ch
 
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019Loiane Groner
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemGuardSquare
 

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

Reactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary GrygleskiReactive for the Impatient - Mary Grygleski
Reactive for the Impatient - Mary Grygleski
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Petro Gordiievych "From Java 9 to Java 12"
Petro Gordiievych "From Java 9 to Java 12"Petro Gordiievych "From Java 9 to Java 12"
Petro Gordiievych "From Java 9 to Java 12"
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Reactive Microservice And Spring5
Reactive Microservice And Spring5Reactive Microservice And Spring5
Reactive Microservice And Spring5
 
React inter3
React inter3React inter3
React inter3
 
Spring 4-groovy
Spring 4-groovySpring 4-groovy
Spring 4-groovy
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJavaReactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
 
Replication - Nick Carboni - ManageIQ Design Summit 2016
Replication - Nick Carboni - ManageIQ Design Summit 2016Replication - Nick Carboni - ManageIQ Design Summit 2016
Replication - Nick Carboni - ManageIQ Design Summit 2016
 
IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016
 
Java SE 8 & EE 7 Launch
Java SE 8 & EE 7 LaunchJava SE 8 & EE 7 Launch
Java SE 8 & EE 7 Launch
 
Reactive java programming for the impatient
Reactive java programming for the impatientReactive java programming for the impatient
Reactive java programming for the impatient
 
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConfFull-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
Full-Stack Reativo com Spring WebFlux + Angular - FiqueEmCasaConf
 
Microservices and modularity with java
Microservices and modularity with javaMicroservices and modularity with java
Microservices and modularity with java
 
soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6
 
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
Full-Stack Reactive with Spring WebFlux + Angular - JConf Colombia 2019
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 

Último

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Reactive Functional Programming with Java 8 on Android N

  • 1. Reactive Functional Programming with Java 8 on Android N Shipeng Xu May 6th 2016
  • 4. An Observable emits items. A Subscriber consumes those items. (from RxJava in practice) Observable Subscriber Items Observable & Subscriber
  • 7. Quick example • Find all png images under a folder • Load the images into a gallery view
  • 8. 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
  • 9. 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
  • 10. 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:
  • 11. 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
  • 13.
  • 15. 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 } }
  • 16. 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
  • 18. 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
  • 19. 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
  • 20. 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); }); });
  • 21. 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); }); });