SlideShare a Scribd company logo
1 of 57
Download to read offline
Functional Reactive Programming on 
Android 
Sam Lee 
2014/11/22 @Mosut x Taina.py x FP 
http://misgod.github.io/Slide-FRP-Android/ 第 1 ⾴
About Me 
Sam Lee (misgod.tw@gmail.com) 
A software engineer lives in Tainan 
Work for htc 
Most used Clojure, Scala and Java 
Interested in Functional Programming 
Interested in Machine Learning and Data Analyst 
· 
· 
· 
· 
· 
http://misgod.github.io/Slide-FRP-Android/ 第 2 ⾴
What Is Functional Reactive Programming 
A style of programming based on two key ideas: continuous time-varying behaviors, and 
event-based reactivity 
Try it 
aObservable.map(x -> x*x) //Square 
.reduce((a, b) -> a+b) //Sum 
.subscribe(x -> println(x)); //Show 
http://misgod.github.io/Slide-FRP-Android/ 第 3 ⾴
Why Functional Reactive Programming 
Writing concurrent programs · correct is di2cult. 
You can transform & compose asynchronous operations. 
High-level abstractions 
Standard error handling 
· 
· 
· 
http://misgod.github.io/Slide-FRP-Android/ 第 4 ⾴
Say Hello to Rx family 
Java: RxJava 
Scala: RxScala 
Clojure: RxClojure 
Groovy: RxGroovy 
JRuby: RxJRuby 
JavaScript: RxJS 
C#: Rx.NET 
C#(Unity): UniRx 
C++: RxCpp 
Ruby: Rx.rb 
Python: RxPY 
Kotlin: RxKotlin 
· 
· 
· 
· 
· 
· 
· 
· 
· 
· 
· 
· 
http://misgod.github.io/Slide-FRP-Android/ 第 5 ⾴
Introduce to RxJava 
https://github.com/ReactiveX/RxJava 
RxJava is a JVM implementation of Reactive Extensions 
RxJava extends Observer pattern to support data/event and compose operators in 
abstract. 
Built by NetBix 
Support Java 6+ & Android 2.3+ 
Java 8 lambda support 
· 
· 
· 
· 
· 
http://misgod.github.io/Slide-FRP-Android/ 第 6 ⾴
Asynchronous sequences of multiple items 
SINGLE ITEMS MULTIPLE ITEMS 
synchronous T getData() Iterable<T> getData() 
asynchronous Future<T> getData() Observable<T> getData() 
http://misgod.github.io/Slide-FRP-Android/ 第 7 ⾴
Observable is "dual" to Iterable 
EVENT ITERABLE (PULL) OBSERVABLE (PUSH) 
retrieve data T next() onNext(T) 
discover error throws Exception onError(Exception) 
complete !hasNext() onCompleted() 
http://csl.stanford.edu/~christos/pldi2010.Gt/meijer.duality.pdf 
http://misgod.github.io/Slide-FRP-Android/ 第 8 ⾴
Observable & Observer 
pushman.subscribe(new Action1<Integer>() { 
@Override 
public void call(Integer x) { 
println("receive: " + x); 
} 
}); 
http://misgod.github.io/Slide-FRP-Android/ 第 9 ⾴
Observer pattern 
http://misgod.github.io/Slide-FRP-Android/ 第 10 ⾴
Functional Reactive 
http://misgod.github.io/Slide-FRP-Android/ 第 11 ⾴
Lambda Expression 
http://misgod.github.io/Slide-FRP-Android/ 第 12 ⾴
Original 
aObservable.filter(new Func1<Integer, Boolean>() { 
public Boolean call(Integer n) { 
return n % 2 == 0; 
} 
}) 
.map(new Func1<Integer, Integer>() { 
public Integer call(Integer n) { 
return n * n; 
} 
}) 
.subscribe(new Action1<Integer>() { 
public void call(Integer n) { 
System.out.println(n); 
} 
}); 
· WTF... 
http://misgod.github.io/Slide-FRP-Android/ 第 13 ⾴
Java 8 lambda 
aObservable.filter(n -> n % 2 == 0) 
.map(n -> n * n) 
.subscribe(System.out::println); 
· but ... no java8 on Davilk(Android) 
http://misgod.github.io/Slide-FRP-Android/ 第 14 ⾴
Retrolambda 
Retrolambda lets you run Java 8 code with lambda expressions and 
method references on Java 7 or lower. 
Retrolambda 
Gradle plugin 
· 
https://github.com/orfjackal/- retrolambda 
· 
- https://github.com/evant/gradle-retrolambda 
http://misgod.github.io/Slide-FRP-Android/ 第 15 ⾴
Retrolambda 
http://misgod.github.io/Slide-FRP-Android/ 第 16 ⾴
rx.Observable 
http://misgod.github.io/Slide-FRP-Android/ 第 17 ⾴
Creating Observable - just 
Observable<List<String>> ob = Observable.just(aList); 
Observable<String> ob2 = Observable.just("Some String"); 
http://misgod.github.io/Slide-FRP-Android/ 第 18 ⾴
Creating Observable - from 
List<String> aList = ...; 
Observable<String> ob = Observable.from(aList); 
http://misgod.github.io/Slide-FRP-Android/ 第 19 ⾴
Creating Observable - create 
http://misgod.github.io/Slide-FRP-Android/ 第 20 ⾴
Creating Observable - create 
ob = Observable.create(subscriber -> { 
try { 
for (String s : aList) { 
if (subscriber.isUnsubscribed()) 
return; 
subscriber.onNext(s); 
} 
subscriber.onCompleted(); 
} catch (Exception e) { 
subscriber.onError(e); 
} 
}); 
http://misgod.github.io/Slide-FRP-Android/ 第 21 ⾴
Creating Observable ... 
repeat( ) 
range( ) 
interval( ) 
timer( ) 
empty( ) 
error( ) 
· 
· 
· 
· 
· 
· 
https://github.com/ReactiveX/RxJava/wiki/Creating-Observables 
http://misgod.github.io/Slide-FRP-Android/ 第 22 ⾴
Transforming Observables - map 
http://misgod.github.io/Slide-FRP-Android/ 第 23 ⾴
Transforming Observables - map 
Observable.range(0, 5) 
.map(x -> toBinaryString(x*x)) 
.subscribe(s -> println(s), 
err -> err.printStackTrace(), 
() -> println("done")); 
0 
1 
100 
1001 
10000 
done 
http://misgod.github.io/Slide-FRP-Android/ 第 24 ⾴
Transforming Observables - flatmap 
http://misgod.github.io/Slide-FRP-Android/ 第 25 ⾴
Transforming Observables - flatmap 
Observable.range(1, 3) 
.flatMap(x -> Observable.just(x).repeat(x)) 
.subscribe(System.out::println); 
1 
2 
2 
3 
3 
3 
· Observable is a Monad 
unit (return) ==> just 
join (bind, >>=) ==> atmap 
- 
- 
http://misgod.github.io/Slide-FRP-Android/ 第 26 ⾴
Transforming Observables - concatmap 
http://misgod.github.io/Slide-FRP-Android/ 第 27 ⾴
Filtering Observables 
http://misgod.github.io/Slide-FRP-Android/ 第 28 ⾴
Filtering Observables 
Observable.range(0, 10) 
.filter(x - (x % 2) == 0) 
.subscribe(System.out::println); 
0 
2 
4 
6 
8 
http://misgod.github.io/Slide-FRP-Android/ 第 29 ⾴
Filtering Observables 
distinct( ) 
Grst( ) 
take( ) 
skip( ) 
elementAt( ) 
sample( ) 
more... 
· 
· 
· 
· 
· 
· 
· 
https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables 
http://misgod.github.io/Slide-FRP-Android/ 第 30 ⾴
Aggregate Operators - reduce 
http://misgod.github.io/Slide-FRP-Android/ 第 31 ⾴
Aggregate Operators - reduce 
Observable.range(1, 10) 
.reduce((a, b) - a*b) 
.subscribe(System.out::println); 
3628800 
http://misgod.github.io/Slide-FRP-Android/ 第 32 ⾴
Aggregate Operators - concat 
http://misgod.github.io/Slide-FRP-Android/ 第 33 ⾴
Combining Observables - merge 
http://misgod.github.io/Slide-FRP-Android/ 第 34 ⾴
Combining Observables - merge 
ObservableString lower = Observable.from(new String[]{a, b, c}); 
ObservableString upper = Observable.from(new String[]{A, B, C}); 
Observable.merge(lower,upper).subscribe(System.out::println); 
/* Or */ 
lower.mergeWith(upper).subscribe(System.out::println); 
a 
b 
A 
c 
B 
C 
http://misgod.github.io/Slide-FRP-Android/ 第 35 ⾴
Combining Observables - startWith 
http://misgod.github.io/Slide-FRP-Android/ 第 36 ⾴
Combining Observables - startWith 
ObservableString lower = Observable.from(new String[]{a, b, c}); 
ObservableString upper = Observable.from(new String[]{A, B, C}); 
lower.startWith(upper).subscribe(System.out::println); 
A 
B 
C 
a 
b 
c 
http://misgod.github.io/Slide-FRP-Android/ 第 37 ⾴
Combining Observables - zip 
http://misgod.github.io/Slide-FRP-Android/ 第 38 ⾴
Combining Observables - zip 
ObservableString lower = Observable.from(new String[]{a, b, c}); 
ObservableString upper = Observable.from(new String[]{A, B, C}); 
Observable.zip(lower, upper, Pair::create) 
.map(pair - pair.first +_ +pair.second) 
.subscribe(System.out::println); 
a_A 
b_B 
c_C 
http://misgod.github.io/Slide-FRP-Android/ 第 39 ⾴
Error Handling 
OnErrorResumeNext 
OnErrorReturn 
retry 
· 
· 
· 
https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators 
http://misgod.github.io/Slide-FRP-Android/ 第 40 ⾴
Threading 
observeOn 
specify on which Scheduler a Subscriber should observe the Observable 
subscribeOn 
specify which Scheduler an Observable should use when its subscription is invoked 
https://github.com/ReactiveX/RxJava/wiki/Scheduler 
http://misgod.github.io/Slide-FRP-Android/ 第 41 ⾴
Subjects 
A Subject = Subscriber + Observable 
http://misgod.github.io/Slide-FRP-Android/ 第 42 ⾴
Subjects 
PublishSubject 
BehaviorSubject 
AsyncSubject 
ReplaySubject 
· 
· 
· 
· 
https://github.com/ReactiveX/RxJava/wiki/Subject 
http://misgod.github.io/Slide-FRP-Android/ 第 43 ⾴
Subjects - How to use 
Subscriber ----- Observable 
PublishSubjectInteger subject = PublishSubject.create(); 
//Observable 
subject.map(x - x*x) 
.subscribe(o - println(o)); 
subject.map(x - x+1) 
.subscribe(o - println(o)); 
//Subscriber 
subject.onNext(11); 
subject.onNext(11); 
subject.onCompleted(); 
Masking a Subject as an Observable - aSubject.· asObservable() 
http://misgod.github.io/Slide-FRP-Android/ 第 44 ⾴
Hot and Cold Observables 
A “cold” Observable waits to emitting items until 
observer subscribes , and so an observer can see the 
whole sequenceg. 
· 
A “hot” Observable may begins emitting items as soon 
as it is created. 
· 
http://misgod.github.io/Slide-FRP-Android/ 第 45 ⾴
RxJava on Android 
http://misgod.github.io/Slide-FRP-Android/ 第 46 ⾴
About Android Development 
Developing a robust app is painful 
Developing a good UX app is painful 
Thread, Executor, Handler, AsyncTask, Loader ... 
RxJava can mitigate your pain 
RetroGt supports methods with a return type of rx.Observable 
· 
life cycle, async, event, state, threading, - error handling 
· 
- interactive, realtime, smooth, animation 
· 
· 
· 
@GET(/user/{id}/photo) 
ObservablePhoto getUserPhoto(@Path(id) int id); 
http://misgod.github.io/Slide-FRP-Android/ 第 47 ⾴
RxAndroid 
Android speciGc bindings for RxJava. 
https://github.com/- ReactiveX/RxAndroid 
Scheduler on main UI thread or a given Android Handler thread. 
AndroidSchedulers 
HandlerThreadScheduler 
- 
- 
Reactive components for common Android use cases and UI widgets 
· 
· 
· 
AndroidObservable 
ViewObservable 
- 
- 
Don't forget to unsubscribe to avoid memory leak! 
http://misgod.github.io/Slide-FRP-Android/ 第 48 ⾴
Thinking in Functional Reactive 
http://misgod.github.io/Slide-FRP-Android/ 第 49 ⾴
Case 1 - Say Hello to Callback Hell 
/* API */ 
void getFromServer(String key, Action1String callback); 
void getFromDB(String key, Action1String callback); 
/* Code */ 
btnClick.setOnClickListener(new View.OnClickListener() { 
public void onClick(View view) { 
getFromDB(myid, new Action1String() { 
public void call(String s) { 
getFromServer(s, new Action1String() { 
public void call(final String s) { 
runOnUiThread(new Runnable() { 
public void run() { 
Toast.makeText(context, s, LENGTH_LONG).show(); 
} 
}); 
/* ... a lot of }) ... */ 
http://misgod.github.io/Slide-FRP-Android/ 第 50 ⾴
Case 1 - Say Hello to Callback Hell 
Using Lambda expression 
btnClick.setOnClickListener(view - 
getFromDB(myid, 
s - getFromServer(s, 
x - runOnUiThread( 
() - Toast.makeText(context, x, LENGTH_LONG).show())))); 
· Shorter but not easy to read 
http://misgod.github.io/Slide-FRP-Android/ 第 51 ⾴
Case 1 - Say Goodbye to Callback Hell 
Using rx.Observable 
/* API */ 
ObservableString getFromServer(String key); 
ObservableString getFromDB(String key); 
/* Code */ 
ViewObservable.clicks(btnClick) 
.map(x - myid) 
.observeOn(Schedulers.io()) 
.flatMap(this::getFromDB) 
.flatMap(this::getFromServer) 
.observeOn(AndroidSchedulers.mainThread()) 
.subscribe(x - Toast.makeText(context, x, LENGTH_LONG).show()); 
http://misgod.github.io/Slide-FRP-Android/ 第 52 ⾴
Case 2 - All In One search 
Requirements 
A search engine includes google/yahoo/1. bing search results. 
2. Should search diNerent engines in parallel 
3. Retry 3 times when search fail 
4. remove redundant url 
ObservableSearchResult g = googleSearch.search(keyword).retry(3); 
ObservableSearchResult b = bingSearch.search(keyword).retry(3); 
ObservableSearchResult y = yahooSearch.search(keyword).retry(3); 
Observable.merge(g, b, y) 
.distinct(site - site.url) 
.observeOn(AndroidSchedulers.mainThread()) 
.subscribe(site - appendDataForUI() , 
err - errorhandle(err)); 
http://misgod.github.io/Slide-FRP-Android/ 第 53 ⾴
Case 3 - A simple EventBus 
PublishSubjectObject subject = PublishSubject.create(); //Global Singleton 
//...In Class A... 
subject.filter(x - x instanceof DataUpdateAction) 
.subscribe( x - ... doSomething ...); 
//...In Class B... 
subject.filter(x - x instanceof DeleteAction) 
.subscribe( x - ... doSomething ...); 
//...In Class C... 
subject.filter(x - x instanceof RefreshAction) 
.subscribe( x - ... doSomething ...); 
subject.onNext(aDataUpdateAction); 
subject.onNext(aDataUpdateAction; 
subject.onNext(aRefreshAction); 
http://misgod.github.io/Slide-FRP-Android/ 第 54 ⾴
Case 4 - Input Suggestion 
private ObservableString getSuggestion(String prefix) { ... } 
ObservableObservableListString o = 
ViewObservable.text(aEditText) 
.map(event - event.text.toString()) 
.filter(x - x.length()  1) 
.observeOn(Schedulers.io()) 
.map(x - getSuggestion(x).toList()); 
Observable.switchOnNext(o) 
.observeOn(AndroidSchedulers.mainThread()) 
.subscribe(lst - showSuggestion(lst)); 
http://misgod.github.io/Slide-FRP-Android/ 第 55 ⾴
Conclusion 
Functional Reactive makes async/state design 1. straightforward. 
2. RxJava is not just a library. 
3. The most important is Functional Reactive Thinking. 
4. Try It in your next project! 
http://misgod.github.io/Slide-FRP-Android/ 第 56 ⾴
http://misgod.github.io/Slide-FRP-Android/ 第 57 ⾴

More Related Content

What's hot

UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)Yoshifumi Kawai
 
Gradle in a Polyglot World
Gradle in a Polyglot WorldGradle in a Polyglot World
Gradle in a Polyglot WorldSchalk Cronjé
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programmingEric Polerecky
 
[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtooling[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtoolingDouglas Chen
 
How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageablecorehard_by
 
Using the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentSchalk Cronjé
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
Build microservice with gRPC in golang
Build microservice with gRPC in golangBuild microservice with gRPC in golang
Build microservice with gRPC in golangTing-Li Chou
 
Hiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceHiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceJesse Vincent
 
Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me? Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me? DVClub
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonYi-Lung Tsai
 
不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)Douglas Chen
 
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment PipelinesSymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment Pipelinescpsitgmbh
 
Node.js/io.js Native C++ Addons
Node.js/io.js Native C++ AddonsNode.js/io.js Native C++ Addons
Node.js/io.js Native C++ AddonsChris Barber
 
NovaProva, a new generation unit test framework for C programs
NovaProva, a new generation unit test framework for C programsNovaProva, a new generation unit test framework for C programs
NovaProva, a new generation unit test framework for C programsGreg Banks
 
Oredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsOredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsAnton Arhipov
 
Java Hates Linux. Deal With It.
Java Hates Linux.  Deal With It.Java Hates Linux.  Deal With It.
Java Hates Linux. Deal With It.Greg Banks
 
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat Pôle Systematic Paris-Region
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGuillaume Laforge
 
Con-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistCon-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistAnton Arhipov
 

What's hot (20)

UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)
 
Gradle in a Polyglot World
Gradle in a Polyglot WorldGradle in a Polyglot World
Gradle in a Polyglot World
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
 
[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtooling[COSCUP 2020] How to use llvm frontend library-libtooling
[COSCUP 2020] How to use llvm frontend library-libtooling
 
How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageable
 
Using the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM Development
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Build microservice with gRPC in golang
Build microservice with gRPC in golangBuild microservice with gRPC in golang
Build microservice with gRPC in golang
 
Hiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceHiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret Sauce
 
Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me? Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me?
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded Python
 
不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)
 
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment PipelinesSymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
 
Node.js/io.js Native C++ Addons
Node.js/io.js Native C++ AddonsNode.js/io.js Native C++ Addons
Node.js/io.js Native C++ Addons
 
NovaProva, a new generation unit test framework for C programs
NovaProva, a new generation unit test framework for C programsNovaProva, a new generation unit test framework for C programs
NovaProva, a new generation unit test framework for C programs
 
Oredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsOredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java Agents
 
Java Hates Linux. Deal With It.
Java Hates Linux.  Deal With It.Java Hates Linux.  Deal With It.
Java Hates Linux. Deal With It.
 
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
 
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume LaforgeGroovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
 
Con-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistCon-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With Javassist
 

Similar to Functional Reactive Programming on Android

LeakPair: Proactive Repairing of Leaks in Single Page Web Applications
LeakPair: Proactive Repairing of Leaks in Single Page Web ApplicationsLeakPair: Proactive Repairing of Leaks in Single Page Web Applications
LeakPair: Proactive Repairing of Leaks in Single Page Web ApplicationsDongsun Kim
 
Android Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondAndroid Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondRamon Ribeiro Rabello
 
[Droidcon Paris 2013]Multi-Versioning Android Tips
[Droidcon Paris 2013]Multi-Versioning Android Tips[Droidcon Paris 2013]Multi-Versioning Android Tips
[Droidcon Paris 2013]Multi-Versioning Android TipsKenichi Kambara
 
Session #6 loaders and adapters
Session #6  loaders and adaptersSession #6  loaders and adapters
Session #6 loaders and adaptersVitali Pekelis
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacriptLei Kang
 
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)Christian Catalan
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run themFilipe Ximenes
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with trackerDesignveloper
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahNick Plante
 
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptProgscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptJohn Stevenson
 
Shift Remote: Mobile - Devops-ify your life with Github Actions - Nicola Cort...
Shift Remote: Mobile - Devops-ify your life with Github Actions - Nicola Cort...Shift Remote: Mobile - Devops-ify your life with Github Actions - Nicola Cort...
Shift Remote: Mobile - Devops-ify your life with Github Actions - Nicola Cort...Shift Conference
 
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
 
From Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practiceFrom Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practiceStefanTomm
 
The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202Mahmoud Samir Fayed
 
Using Git as your VCS with Bioconductor
Using Git as your VCS with BioconductorUsing Git as your VCS with Bioconductor
Using Git as your VCS with Bioconductortimyates
 
jRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServicejRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServiceGunnar Hillert
 

Similar to Functional Reactive Programming on Android (20)

LeakPair: Proactive Repairing of Leaks in Single Page Web Applications
LeakPair: Proactive Repairing of Leaks in Single Page Web ApplicationsLeakPair: Proactive Repairing of Leaks in Single Page Web Applications
LeakPair: Proactive Repairing of Leaks in Single Page Web Applications
 
Android Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondAndroid Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyond
 
[Droidcon Paris 2013]Multi-Versioning Android Tips
[Droidcon Paris 2013]Multi-Versioning Android Tips[Droidcon Paris 2013]Multi-Versioning Android Tips
[Droidcon Paris 2013]Multi-Versioning Android Tips
 
How to Build & Use OpenCL on OpenCV & Android NDK
How to Build & Use OpenCL on OpenCV & Android NDKHow to Build & Use OpenCL on OpenCV & Android NDK
How to Build & Use OpenCL on OpenCV & Android NDK
 
Session #6 loaders and adapters
Session #6  loaders and adaptersSession #6  loaders and adapters
Session #6 loaders and adapters
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
 
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in ClojurescriptProgscon 2017: Taming the wild fronteer - Adventures in Clojurescript
Progscon 2017: Taming the wild fronteer - Adventures in Clojurescript
 
Shift Remote: Mobile - Devops-ify your life with Github Actions - Nicola Cort...
Shift Remote: Mobile - Devops-ify your life with Github Actions - Nicola Cort...Shift Remote: Mobile - Devops-ify your life with Github Actions - Nicola Cort...
Shift Remote: Mobile - Devops-ify your life with Github Actions - Nicola Cort...
 
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
 
From Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practiceFrom Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practice
 
The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202
 
F3X12 FLOW3 Project Lifecycle
F3X12 FLOW3 Project LifecycleF3X12 FLOW3 Project Lifecycle
F3X12 FLOW3 Project Lifecycle
 
Using Git as your VCS with Bioconductor
Using Git as your VCS with BioconductorUsing Git as your VCS with Bioconductor
Using Git as your VCS with Bioconductor
 
jRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServicejRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting Service
 
Core Android
Core AndroidCore Android
Core Android
 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
 

Recently uploaded

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Functional Reactive Programming on Android

  • 1. Functional Reactive Programming on Android Sam Lee 2014/11/22 @Mosut x Taina.py x FP http://misgod.github.io/Slide-FRP-Android/ 第 1 ⾴
  • 2. About Me Sam Lee (misgod.tw@gmail.com) A software engineer lives in Tainan Work for htc Most used Clojure, Scala and Java Interested in Functional Programming Interested in Machine Learning and Data Analyst · · · · · http://misgod.github.io/Slide-FRP-Android/ 第 2 ⾴
  • 3. What Is Functional Reactive Programming A style of programming based on two key ideas: continuous time-varying behaviors, and event-based reactivity Try it aObservable.map(x -> x*x) //Square .reduce((a, b) -> a+b) //Sum .subscribe(x -> println(x)); //Show http://misgod.github.io/Slide-FRP-Android/ 第 3 ⾴
  • 4. Why Functional Reactive Programming Writing concurrent programs · correct is di2cult. You can transform & compose asynchronous operations. High-level abstractions Standard error handling · · · http://misgod.github.io/Slide-FRP-Android/ 第 4 ⾴
  • 5. Say Hello to Rx family Java: RxJava Scala: RxScala Clojure: RxClojure Groovy: RxGroovy JRuby: RxJRuby JavaScript: RxJS C#: Rx.NET C#(Unity): UniRx C++: RxCpp Ruby: Rx.rb Python: RxPY Kotlin: RxKotlin · · · · · · · · · · · · http://misgod.github.io/Slide-FRP-Android/ 第 5 ⾴
  • 6. Introduce to RxJava https://github.com/ReactiveX/RxJava RxJava is a JVM implementation of Reactive Extensions RxJava extends Observer pattern to support data/event and compose operators in abstract. Built by NetBix Support Java 6+ & Android 2.3+ Java 8 lambda support · · · · · http://misgod.github.io/Slide-FRP-Android/ 第 6 ⾴
  • 7. Asynchronous sequences of multiple items SINGLE ITEMS MULTIPLE ITEMS synchronous T getData() Iterable<T> getData() asynchronous Future<T> getData() Observable<T> getData() http://misgod.github.io/Slide-FRP-Android/ 第 7 ⾴
  • 8. Observable is "dual" to Iterable EVENT ITERABLE (PULL) OBSERVABLE (PUSH) retrieve data T next() onNext(T) discover error throws Exception onError(Exception) complete !hasNext() onCompleted() http://csl.stanford.edu/~christos/pldi2010.Gt/meijer.duality.pdf http://misgod.github.io/Slide-FRP-Android/ 第 8 ⾴
  • 9. Observable & Observer pushman.subscribe(new Action1<Integer>() { @Override public void call(Integer x) { println("receive: " + x); } }); http://misgod.github.io/Slide-FRP-Android/ 第 9 ⾴
  • 13. Original aObservable.filter(new Func1<Integer, Boolean>() { public Boolean call(Integer n) { return n % 2 == 0; } }) .map(new Func1<Integer, Integer>() { public Integer call(Integer n) { return n * n; } }) .subscribe(new Action1<Integer>() { public void call(Integer n) { System.out.println(n); } }); · WTF... http://misgod.github.io/Slide-FRP-Android/ 第 13 ⾴
  • 14. Java 8 lambda aObservable.filter(n -> n % 2 == 0) .map(n -> n * n) .subscribe(System.out::println); · but ... no java8 on Davilk(Android) http://misgod.github.io/Slide-FRP-Android/ 第 14 ⾴
  • 15. Retrolambda Retrolambda lets you run Java 8 code with lambda expressions and method references on Java 7 or lower. Retrolambda Gradle plugin · https://github.com/orfjackal/- retrolambda · - https://github.com/evant/gradle-retrolambda http://misgod.github.io/Slide-FRP-Android/ 第 15 ⾴
  • 18. Creating Observable - just Observable<List<String>> ob = Observable.just(aList); Observable<String> ob2 = Observable.just("Some String"); http://misgod.github.io/Slide-FRP-Android/ 第 18 ⾴
  • 19. Creating Observable - from List<String> aList = ...; Observable<String> ob = Observable.from(aList); http://misgod.github.io/Slide-FRP-Android/ 第 19 ⾴
  • 20. Creating Observable - create http://misgod.github.io/Slide-FRP-Android/ 第 20 ⾴
  • 21. Creating Observable - create ob = Observable.create(subscriber -> { try { for (String s : aList) { if (subscriber.isUnsubscribed()) return; subscriber.onNext(s); } subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } }); http://misgod.github.io/Slide-FRP-Android/ 第 21 ⾴
  • 22. Creating Observable ... repeat( ) range( ) interval( ) timer( ) empty( ) error( ) · · · · · · https://github.com/ReactiveX/RxJava/wiki/Creating-Observables http://misgod.github.io/Slide-FRP-Android/ 第 22 ⾴
  • 23. Transforming Observables - map http://misgod.github.io/Slide-FRP-Android/ 第 23 ⾴
  • 24. Transforming Observables - map Observable.range(0, 5) .map(x -> toBinaryString(x*x)) .subscribe(s -> println(s), err -> err.printStackTrace(), () -> println("done")); 0 1 100 1001 10000 done http://misgod.github.io/Slide-FRP-Android/ 第 24 ⾴
  • 25. Transforming Observables - flatmap http://misgod.github.io/Slide-FRP-Android/ 第 25 ⾴
  • 26. Transforming Observables - flatmap Observable.range(1, 3) .flatMap(x -> Observable.just(x).repeat(x)) .subscribe(System.out::println); 1 2 2 3 3 3 · Observable is a Monad unit (return) ==> just join (bind, >>=) ==> atmap - - http://misgod.github.io/Slide-FRP-Android/ 第 26 ⾴
  • 27. Transforming Observables - concatmap http://misgod.github.io/Slide-FRP-Android/ 第 27 ⾴
  • 29. Filtering Observables Observable.range(0, 10) .filter(x - (x % 2) == 0) .subscribe(System.out::println); 0 2 4 6 8 http://misgod.github.io/Slide-FRP-Android/ 第 29 ⾴
  • 30. Filtering Observables distinct( ) Grst( ) take( ) skip( ) elementAt( ) sample( ) more... · · · · · · · https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables http://misgod.github.io/Slide-FRP-Android/ 第 30 ⾴
  • 31. Aggregate Operators - reduce http://misgod.github.io/Slide-FRP-Android/ 第 31 ⾴
  • 32. Aggregate Operators - reduce Observable.range(1, 10) .reduce((a, b) - a*b) .subscribe(System.out::println); 3628800 http://misgod.github.io/Slide-FRP-Android/ 第 32 ⾴
  • 33. Aggregate Operators - concat http://misgod.github.io/Slide-FRP-Android/ 第 33 ⾴
  • 34. Combining Observables - merge http://misgod.github.io/Slide-FRP-Android/ 第 34 ⾴
  • 35. Combining Observables - merge ObservableString lower = Observable.from(new String[]{a, b, c}); ObservableString upper = Observable.from(new String[]{A, B, C}); Observable.merge(lower,upper).subscribe(System.out::println); /* Or */ lower.mergeWith(upper).subscribe(System.out::println); a b A c B C http://misgod.github.io/Slide-FRP-Android/ 第 35 ⾴
  • 36. Combining Observables - startWith http://misgod.github.io/Slide-FRP-Android/ 第 36 ⾴
  • 37. Combining Observables - startWith ObservableString lower = Observable.from(new String[]{a, b, c}); ObservableString upper = Observable.from(new String[]{A, B, C}); lower.startWith(upper).subscribe(System.out::println); A B C a b c http://misgod.github.io/Slide-FRP-Android/ 第 37 ⾴
  • 38. Combining Observables - zip http://misgod.github.io/Slide-FRP-Android/ 第 38 ⾴
  • 39. Combining Observables - zip ObservableString lower = Observable.from(new String[]{a, b, c}); ObservableString upper = Observable.from(new String[]{A, B, C}); Observable.zip(lower, upper, Pair::create) .map(pair - pair.first +_ +pair.second) .subscribe(System.out::println); a_A b_B c_C http://misgod.github.io/Slide-FRP-Android/ 第 39 ⾴
  • 40. Error Handling OnErrorResumeNext OnErrorReturn retry · · · https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators http://misgod.github.io/Slide-FRP-Android/ 第 40 ⾴
  • 41. Threading observeOn specify on which Scheduler a Subscriber should observe the Observable subscribeOn specify which Scheduler an Observable should use when its subscription is invoked https://github.com/ReactiveX/RxJava/wiki/Scheduler http://misgod.github.io/Slide-FRP-Android/ 第 41 ⾴
  • 42. Subjects A Subject = Subscriber + Observable http://misgod.github.io/Slide-FRP-Android/ 第 42 ⾴
  • 43. Subjects PublishSubject BehaviorSubject AsyncSubject ReplaySubject · · · · https://github.com/ReactiveX/RxJava/wiki/Subject http://misgod.github.io/Slide-FRP-Android/ 第 43 ⾴
  • 44. Subjects - How to use Subscriber ----- Observable PublishSubjectInteger subject = PublishSubject.create(); //Observable subject.map(x - x*x) .subscribe(o - println(o)); subject.map(x - x+1) .subscribe(o - println(o)); //Subscriber subject.onNext(11); subject.onNext(11); subject.onCompleted(); Masking a Subject as an Observable - aSubject.· asObservable() http://misgod.github.io/Slide-FRP-Android/ 第 44 ⾴
  • 45. Hot and Cold Observables A “cold” Observable waits to emitting items until observer subscribes , and so an observer can see the whole sequenceg. · A “hot” Observable may begins emitting items as soon as it is created. · http://misgod.github.io/Slide-FRP-Android/ 第 45 ⾴
  • 46. RxJava on Android http://misgod.github.io/Slide-FRP-Android/ 第 46 ⾴
  • 47. About Android Development Developing a robust app is painful Developing a good UX app is painful Thread, Executor, Handler, AsyncTask, Loader ... RxJava can mitigate your pain RetroGt supports methods with a return type of rx.Observable · life cycle, async, event, state, threading, - error handling · - interactive, realtime, smooth, animation · · · @GET(/user/{id}/photo) ObservablePhoto getUserPhoto(@Path(id) int id); http://misgod.github.io/Slide-FRP-Android/ 第 47 ⾴
  • 48. RxAndroid Android speciGc bindings for RxJava. https://github.com/- ReactiveX/RxAndroid Scheduler on main UI thread or a given Android Handler thread. AndroidSchedulers HandlerThreadScheduler - - Reactive components for common Android use cases and UI widgets · · · AndroidObservable ViewObservable - - Don't forget to unsubscribe to avoid memory leak! http://misgod.github.io/Slide-FRP-Android/ 第 48 ⾴
  • 49. Thinking in Functional Reactive http://misgod.github.io/Slide-FRP-Android/ 第 49 ⾴
  • 50. Case 1 - Say Hello to Callback Hell /* API */ void getFromServer(String key, Action1String callback); void getFromDB(String key, Action1String callback); /* Code */ btnClick.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { getFromDB(myid, new Action1String() { public void call(String s) { getFromServer(s, new Action1String() { public void call(final String s) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(context, s, LENGTH_LONG).show(); } }); /* ... a lot of }) ... */ http://misgod.github.io/Slide-FRP-Android/ 第 50 ⾴
  • 51. Case 1 - Say Hello to Callback Hell Using Lambda expression btnClick.setOnClickListener(view - getFromDB(myid, s - getFromServer(s, x - runOnUiThread( () - Toast.makeText(context, x, LENGTH_LONG).show())))); · Shorter but not easy to read http://misgod.github.io/Slide-FRP-Android/ 第 51 ⾴
  • 52. Case 1 - Say Goodbye to Callback Hell Using rx.Observable /* API */ ObservableString getFromServer(String key); ObservableString getFromDB(String key); /* Code */ ViewObservable.clicks(btnClick) .map(x - myid) .observeOn(Schedulers.io()) .flatMap(this::getFromDB) .flatMap(this::getFromServer) .observeOn(AndroidSchedulers.mainThread()) .subscribe(x - Toast.makeText(context, x, LENGTH_LONG).show()); http://misgod.github.io/Slide-FRP-Android/ 第 52 ⾴
  • 53. Case 2 - All In One search Requirements A search engine includes google/yahoo/1. bing search results. 2. Should search diNerent engines in parallel 3. Retry 3 times when search fail 4. remove redundant url ObservableSearchResult g = googleSearch.search(keyword).retry(3); ObservableSearchResult b = bingSearch.search(keyword).retry(3); ObservableSearchResult y = yahooSearch.search(keyword).retry(3); Observable.merge(g, b, y) .distinct(site - site.url) .observeOn(AndroidSchedulers.mainThread()) .subscribe(site - appendDataForUI() , err - errorhandle(err)); http://misgod.github.io/Slide-FRP-Android/ 第 53 ⾴
  • 54. Case 3 - A simple EventBus PublishSubjectObject subject = PublishSubject.create(); //Global Singleton //...In Class A... subject.filter(x - x instanceof DataUpdateAction) .subscribe( x - ... doSomething ...); //...In Class B... subject.filter(x - x instanceof DeleteAction) .subscribe( x - ... doSomething ...); //...In Class C... subject.filter(x - x instanceof RefreshAction) .subscribe( x - ... doSomething ...); subject.onNext(aDataUpdateAction); subject.onNext(aDataUpdateAction; subject.onNext(aRefreshAction); http://misgod.github.io/Slide-FRP-Android/ 第 54 ⾴
  • 55. Case 4 - Input Suggestion private ObservableString getSuggestion(String prefix) { ... } ObservableObservableListString o = ViewObservable.text(aEditText) .map(event - event.text.toString()) .filter(x - x.length() 1) .observeOn(Schedulers.io()) .map(x - getSuggestion(x).toList()); Observable.switchOnNext(o) .observeOn(AndroidSchedulers.mainThread()) .subscribe(lst - showSuggestion(lst)); http://misgod.github.io/Slide-FRP-Android/ 第 55 ⾴
  • 56. Conclusion Functional Reactive makes async/state design 1. straightforward. 2. RxJava is not just a library. 3. The most important is Functional Reactive Thinking. 4. Try It in your next project! http://misgod.github.io/Slide-FRP-Android/ 第 56 ⾴