SlideShare a Scribd company logo
1 of 159
Download to read offline




































































void task(int num) {
log("begin task " + num);
sleep(1000L); // Work 1, 2,... N
log("end task " + num);
}
...
log("START");
task(1);
log("END");
log("DONE");
work 1 | work 2 | … | work N
void task(int num) {
log("begin task " + num);
sleep(1000L); // Work 1, 2,... N
log("end task " + num);
}
...
log("START");
task(1);
task(2);
task(3);
log("END");
log("DONE");
work 1 | work 2 | … | work N work 1 | work 2 | … | work N work 1 | work 2 | … | work N
class Task implements Runnable {
private final int id;
Task(int id) {
this.id = id;
}
public void run() {
task(id);
}
}
void task(int num) {
log("begin task " + num);
sleep(1000L); // Work 1, 2,... N
log("end task " + num);
}
...
log(“START");
Thread t1, t2, t3;
t1 = new Thread(new Task(1)); t1.start();
t2 = new Thread(new Task(2)); t2.start();
t3 = new Thread(new Task(3)); t3.start();
log("END");
t1.join(); t2.join(); t3.join();
log("DONE");
work 1 | work 2 | … | work N
work 1 | work 2 | … | work N
work 1 | work 2 | … | work N
synchronized void task(int num) {
log("begin task " + num);
sleep(1000L); // Work 1, 2,... N
log("end task " + num);
}
...
log("START");
Thread t1, t2, t3;
t1 = new Thread(new Task(1)); t1.start();
t2 = new Thread(new Task(2)); t2.start();
t3 = new Thread(new Task(3)); t3.start();
log("END");
t1.join(); t2.join(); t3.join();
log("DONE");
work 1 | work 2 | … | work N
work 1 | work 2 | … | work N
work 1 | work 2 | … | work N
𝛥
Independent Each Other
Resource Consuming, Heavyweight Task
Order doesn’t Matter (Commutative)
Lightweight Calculation
Independent work part (fork) collecting result part (join)
int total = 0;
int integral(String sector, int from, int to) {
log("Sector %s integral from %d" , sector, from);
sleep((to - from) * 1000L); // integral takes very long time
log("Sector %s integral to %d" , sector, to);
return (to - from) * 1000;
}
synchronized void accumulate(String sector, int partial) {
log("Prepare adding sector %s + %d", sector, partial);
sleep(500L); // accumulation also tasks time
total += partial;
log("Done adding sector %s + %d", sector, partial);
}
class Partial implements Runnable {
final String sector; final int from, to;
Partial(String s, int f, int t) { sector = s; from = f; to = t; }
public void run() {
int partial = integral(sector, from, to);
accumulate(sector, partial);
}
}
t1 = new Thread(new Partial("A",0,5));
t2 = new Thread(new Partial("B",5,10));
t3 = new Thread(new Partial("C",10,15));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
log("RESULT: " + total);
total = integral("ABC", 0, 15);
log("RESULT: " + total);
Thread Spawning Cost User Implemented Work
⨉
⨉
✈
✈
✈
🐌
🐌
🐌
...
Thread Resource User Work
Thread Resource User Work
⨉
⨉
⨉
List<String> list = Arrays.asList("a", "b", "c");
// list is container for “string event”,
// so “x” is string by type inference
list.forEach(x -> log(x.toUpperCase());
List<Integer> list = Arrays.asList(1, 2, 3);
// list is container for “integer event”,
// so “x” is integer by type inference
list.forEach(x -> log(x + x));
http://reactivex.io/intro.html






log("START");
try {
List<Integer> l = // [1, 2, 3, null, 5]
for (Integer each : l) {
log("> just: " + each);
if (!filter(each)) { continue; }
log("> filter: " + each);
Integer y = map(each);
log("> map: " + y);
log("subscribe: " + y);
}
log("completed");
} catch (Throwable t) {
log("error: " + t);
} finally {
log("END");
}
boolean filter(Integer x) {
return x % 2 == 1;
}
Integer map(Integer in) {
return in * 10;
}
log("START");
Observable.just(1, 2, 3, null, 5)
.doOnNext(x -> log("> just: " + x))
.filter(x -> x % 2 == 1)
.doOnNext(x -> log("> filter: " + x))
.map(x -> x * 10)
.doOnNext(x -> log("> map: " + x))
.subscribe(
x -> log("subscribe: " + x),
ex -> log("error: " + ex),
() -> log("completed")
);
log("END");
11.119 [main] START
11.121 [main] > just: 1
11.124 [main] > filter: 1
11.125 [main] > map: 10
11.127 [main] subscribe: 10
11.128 [main] > just: 2
11.129 [main] > just: 3
11.129 [main] > filter: 3
11.130 [main] > map: 30
11.130 [main] subscribe: 30
11.131 [main] > just: null
11.140 [main] error: java.lang.NullPointerException
11.142 [main] END
// List<Event> events = …
try {
for (Event e : events) {
onNextEvent(e);
}
onSuccessfulComplete();
} catch (Throwable t) {
onErrorEvent(t);
}
// List<Event> events = …
try {
events.forEach(e -> onNextEvent(e));
onSuccessfulComplete();
} catch (Throwable t) {
onErrorEvent(t);
}
// Stream<Event> stream = …
try {
stream
.map(e -> transform(e))
// more transformations

.forEach(e -> onNextEvent(e));
onSuccessfulComplete();
} catch (Throwable t) {
onErrorEvent(t);
}
// Observable<Event> observable = …
observable
.map(e -> transform(e))
// more transformations

.subscribe(
e -> onNextEvent(e),
t -> onSuccessfulComplete(),
() -> onErrorEvent(t)
);
// input expressed as: ‘a’, ‘b’, ‘c’
Output hardWork(Input in) {
log("Beginning Work: " + in.id());
// Very HARD WORK such as Network I/O
log("Done Work: " + in.id());
return out;
}
log("start")
observable.map(x -> hardWork(x))
.filter(x -> f(x))
.operator(x -> g(x))
...
.subscribe(x -> log("result: " + x);
log("end");
log("start")
observable.map(x -> hardWork(x))
.filter(x -> f(x))
.operator(x -> g(x))
.subscribeOn(scheduler)
...
.subscribe(x -> log("result: " + x);
log("end");
log("start")
observable
.flatMap(x ->
Observable.fromCallable(() -> hardWork(x))
.subscribeOn(scheduler)
)
.filter(x -> f(x))
.operator(x -> g(x))
...
.subscribe(x -> log("result: " + x);
log("end");
log("start")
observable
.flatMap(x ->
Observable.defer(() ->
Observable.just(hardWork(x))
).subscribeOn(scheduler)
)
.filter(x -> f(x))
.operator(x -> g(x))
...
.subscribe(x -> log("result: " + x);
log("end");
log("prepare");
Observable<Long> a = Observable.just("bread")
.doOnNext(x -> log("substream: " + x))
.map(x -> repository.purchase(x, 1))
.subscribeOn(schedulerA());
Observable<Long> b = Observable.just("cucumber")
.doOnNext(x -> log("substream: " + x))
.map(x -> repository.purchase(x, 3))
.subscribeOn(schedulerA());
Observable<Long> c = Observable.just("beef")
.doOnNext(x -> log("substream: " + x))
.map(x -> repository.purchase(x, 5))
.subscribeOn(schedulerA());
log("start");
Observable.just(a, b, c)
.flatMap(x -> x)
.observeOn(schedulerB())
// .reduce((x, y) -> x.add(y))
.subscribe(x -> log("Q'ty: " + x));
log("end");
Destinations
Quoting
Customers
destination.path("recommended").request().header("Rx-User", "Async").async()
.get(new InvocationCallback<List<Destination>>() {
public void completed(final List<Destination> recommended) {
final CountDownLatch innerLatch = new CountDownLatch(recommended.size());
final Map<String, Forecast> forecasts = Collections.synchronizedMap(new HashMap<>());
for (final Destination dest : recommended) {
forecast.resolveTemplate("destination", dest.getDestination()).request().async()
.get(new InvocationCallback<Forecast>() {
public void completed(final Forecast forecast) {
forecasts.put(dest.getDestination(), forecast); innerLatch.countDown();
}
public void failed(final Throwable throwable) {
errors.offer("Forecast: " + throwable.getMessage()); innerLatch.countDown();
}
});
}
try {
if (!innerLatch.await(10, TimeUnit.SECONDS))
errors.offer("Inner: Waiting for requests to complete has timed out.");
} catch (final InterruptedException e) {
errors.offer("Inner: Waiting for requests to complete has been interrupted.");
}
// Continue with processing.
}
public void failed(final Throwable throwable) { errors.offer("Recommended: " + throwable.getMessage()); }
});
Observable<Destination> recommended = RxObservable.from(dest)
.path("recommended")
.request()
.header("Rx-User", "RxJava")
.rx().get(new GenericType<List<Destination>>() {})
.onErrorReturn(t -> emptyList())
.flatMap(Observable::from)
.cache();
Observable<Forecast> forecasts = recommended.flatMap(dest ->
RxObservable.from(forecast)
.resolveTemplate("destination", dest.getDestination())
.request().rx().get(Forecast.class)
.onErrorReturn(t -> new Forecast(dest.getDestination(), "N/A")
)
);
Observable<Recommendation> recommendations = Observable.zip(
recommended,
forecasts,
Recommendation::new);
Existing Structure (SpringCamp 2016)
user

service
40+ tables
admin

console
client
slave

(MySQL)master

(MySQL)
adjustment
C/R/U/D
update “list” order
fetch “list”
10+ RPCs
C/R/U/D
replicator40+ tables
admin

console
composite json
master

(MySQL)
item data
adjustment
purchase data
#1
#2
Asymmetric Replication (SpringCamp 2016)
user

service
NoSQL replica

(Couchbase) client
List<FixedDeal> fixed = fixedDealService.find(cid, bid);
FixedDealPagination pagination = FixedDealPagination.paginate(fixed, limit);
FixedDealPage currentPage = pagination.find(pageNo);
PaginationOffset offset = PaginationOffset.adjust(currentPage);
List<String> plain = plainDealService.find(cid, bid, offset);
List<String> collatedIds = PageRankCollator.collate(currentPage, plain)
return Observable.from(collatedIds)
.concatMapEager(repository::get)
.map(JsonDocument::content)
.map(stickerFilter::apply)
.map(priceFilter::apply)
.map(viewAttributeFilter::apply)
.toList()
.toBlocking()
.singleOrDefault(Json.DEAL_LIST_DEFAULT);
Observable<FixedDeal> fixed = fixedDealService.prepare(cid, bid, pageNo, limit);
Observable<PlainDeal> plain = plainDealService.prepare(cid, bid, pageNo, limit);
return Observable.zip(fixed, plain, DealId::collate)
.flatMap(DealId::targets)
.concatMapEager(repository::get)
.map(JsonDocument::content)
.map(stickerFilter::apply)
.map(priceFilter::apply)
.map(viewAttributeFilter::apply)
.toList()
.toBlocking()
.singleOrDefault(Json.DEAL_LIST_DEFAULT);
// 1. gather from N tables concurrently, then aggregate
// 2. insert to replica persistence
Observable<Deal> deal = Observable.just(dealNo)
.flatMap(id -> dealRepository.findDeferred(id))
.retry(3)
.onErrorReturn(throwable -> Deal.ERROR);
Observable<DealCategory> category = Observable.just(categoryNo)
.flatMap(id -> dealCategoryRepository.findDeferred(id))
.retry(3)
.onErrorReturn(throwable -> DealCategory.ERROR);
Observable<DealScore> score = Observable.just(dealNo)
.flatMap(id -> dealScoreRepository.findDeferred(id))
.onErrorReturn(throwable -> DealScore.DEFAULT);
Observable.zip(deal, category, score, DealJson::aggregate)
.observeOn(schedulerSlot.dealSourceScheduler())
.subscribe(src -> replicaService.send(src));
Introductory RxJava
Introductory RxJava
Introductory RxJava

More Related Content

What's hot

DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
Sages
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
riue
 

What's hot (20)

DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Rデバッグあれこれ
RデバッグあれこれRデバッグあれこれ
Rデバッグあれこれ
 
Rのスコープとフレームと環境と
Rのスコープとフレームと環境とRのスコープとフレームと環境と
Rのスコープとフレームと環境と
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
The Ring programming language version 1.3 book - Part 50 of 88
The Ring programming language version 1.3 book - Part 50 of 88The Ring programming language version 1.3 book - Part 50 of 88
The Ring programming language version 1.3 book - Part 50 of 88
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programming
 
Java Program
Java ProgramJava Program
Java Program
 
The Ring programming language version 1.8 book - Part 30 of 202
The Ring programming language version 1.8 book - Part 30 of 202The Ring programming language version 1.8 book - Part 30 of 202
The Ring programming language version 1.8 book - Part 30 of 202
 
Data Types and Processing in ES6
Data Types and Processing in ES6Data Types and Processing in ES6
Data Types and Processing in ES6
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and Profit
 
The Ring programming language version 1.4 book - Part 18 of 30
The Ring programming language version 1.4 book - Part 18 of 30The Ring programming language version 1.4 book - Part 18 of 30
The Ring programming language version 1.4 book - Part 18 of 30
 
The Ring programming language version 1.5.3 book - Part 77 of 184
The Ring programming language version 1.5.3 book - Part 77 of 184The Ring programming language version 1.5.3 book - Part 77 of 184
The Ring programming language version 1.5.3 book - Part 77 of 184
 
BingoConsoleApp
BingoConsoleAppBingoConsoleApp
BingoConsoleApp
 
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiMonitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
 
ReactiveCocoa workshop
ReactiveCocoa workshopReactiveCocoa workshop
ReactiveCocoa workshop
 

Similar to Introductory RxJava

オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
Takayuki Goto
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
julien.ponge
 

Similar to Introductory RxJava (20)

オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
 
Javascript
JavascriptJavascript
Javascript
 
Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
PRACTICAL COMPUTING
PRACTICAL COMPUTINGPRACTICAL COMPUTING
PRACTICAL COMPUTING
 
Christian Gill ''Functional programming for the people''
Christian Gill ''Functional programming for the people''Christian Gill ''Functional programming for the people''
Christian Gill ''Functional programming for the people''
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
 
TDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação FuncionalTDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação Funcional
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Corona sdk
Corona sdkCorona sdk
Corona sdk
 
Monadologie
MonadologieMonadologie
Monadologie
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
 

Recently uploaded

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Introductory RxJava

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 12.
  • 14.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 22.
  • 23.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35. void task(int num) { log("begin task " + num); sleep(1000L); // Work 1, 2,... N log("end task " + num); } ... log("START"); task(1); log("END"); log("DONE");
  • 36. work 1 | work 2 | … | work N
  • 37.
  • 38. void task(int num) { log("begin task " + num); sleep(1000L); // Work 1, 2,... N log("end task " + num); } ... log("START"); task(1); task(2); task(3); log("END"); log("DONE");
  • 39. work 1 | work 2 | … | work N work 1 | work 2 | … | work N work 1 | work 2 | … | work N
  • 40.
  • 41. class Task implements Runnable { private final int id; Task(int id) { this.id = id; } public void run() { task(id); } }
  • 42.
  • 43. void task(int num) { log("begin task " + num); sleep(1000L); // Work 1, 2,... N log("end task " + num); } ... log(“START"); Thread t1, t2, t3; t1 = new Thread(new Task(1)); t1.start(); t2 = new Thread(new Task(2)); t2.start(); t3 = new Thread(new Task(3)); t3.start(); log("END"); t1.join(); t2.join(); t3.join(); log("DONE");
  • 44. work 1 | work 2 | … | work N work 1 | work 2 | … | work N work 1 | work 2 | … | work N
  • 45.
  • 46. synchronized void task(int num) { log("begin task " + num); sleep(1000L); // Work 1, 2,... N log("end task " + num); } ... log("START"); Thread t1, t2, t3; t1 = new Thread(new Task(1)); t1.start(); t2 = new Thread(new Task(2)); t2.start(); t3 = new Thread(new Task(3)); t3.start(); log("END"); t1.join(); t2.join(); t3.join(); log("DONE");
  • 47. work 1 | work 2 | … | work N work 1 | work 2 | … | work N work 1 | work 2 | … | work N
  • 48.
  • 49.
  • 50.
  • 51. 𝛥
  • 52.
  • 53.
  • 54. Independent Each Other Resource Consuming, Heavyweight Task
  • 55. Order doesn’t Matter (Commutative) Lightweight Calculation
  • 56. Independent work part (fork) collecting result part (join)
  • 57.
  • 58. int total = 0; int integral(String sector, int from, int to) { log("Sector %s integral from %d" , sector, from); sleep((to - from) * 1000L); // integral takes very long time log("Sector %s integral to %d" , sector, to); return (to - from) * 1000; } synchronized void accumulate(String sector, int partial) { log("Prepare adding sector %s + %d", sector, partial); sleep(500L); // accumulation also tasks time total += partial; log("Done adding sector %s + %d", sector, partial); } class Partial implements Runnable { final String sector; final int from, to; Partial(String s, int f, int t) { sector = s; from = f; to = t; } public void run() { int partial = integral(sector, from, to); accumulate(sector, partial); } }
  • 59.
  • 60. t1 = new Thread(new Partial("A",0,5)); t2 = new Thread(new Partial("B",5,10)); t3 = new Thread(new Partial("C",10,15)); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); log("RESULT: " + total);
  • 61.
  • 62.
  • 63. total = integral("ABC", 0, 15); log("RESULT: " + total);
  • 64.
  • 65.
  • 66.
  • 67.
  • 68. Thread Spawning Cost User Implemented Work
  • 69.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 79.
  • 80.
  • 81. Thread Resource User Work Thread Resource User Work
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101. List<String> list = Arrays.asList("a", "b", "c"); // list is container for “string event”, // so “x” is string by type inference list.forEach(x -> log(x.toUpperCase()); List<Integer> list = Arrays.asList(1, 2, 3); // list is container for “integer event”, // so “x” is integer by type inference list.forEach(x -> log(x + x));
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 109.
  • 110.
  • 112.
  • 113.
  • 114. log("START"); try { List<Integer> l = // [1, 2, 3, null, 5] for (Integer each : l) { log("> just: " + each); if (!filter(each)) { continue; } log("> filter: " + each); Integer y = map(each); log("> map: " + y); log("subscribe: " + y); } log("completed"); } catch (Throwable t) { log("error: " + t); } finally { log("END"); } boolean filter(Integer x) { return x % 2 == 1; } Integer map(Integer in) { return in * 10; } log("START"); Observable.just(1, 2, 3, null, 5) .doOnNext(x -> log("> just: " + x)) .filter(x -> x % 2 == 1) .doOnNext(x -> log("> filter: " + x)) .map(x -> x * 10) .doOnNext(x -> log("> map: " + x)) .subscribe( x -> log("subscribe: " + x), ex -> log("error: " + ex), () -> log("completed") ); log("END"); 11.119 [main] START 11.121 [main] > just: 1 11.124 [main] > filter: 1 11.125 [main] > map: 10 11.127 [main] subscribe: 10 11.128 [main] > just: 2 11.129 [main] > just: 3 11.129 [main] > filter: 3 11.130 [main] > map: 30 11.130 [main] subscribe: 30 11.131 [main] > just: null 11.140 [main] error: java.lang.NullPointerException 11.142 [main] END
  • 115.
  • 116. // List<Event> events = … try { for (Event e : events) { onNextEvent(e); } onSuccessfulComplete(); } catch (Throwable t) { onErrorEvent(t); }
  • 117. // List<Event> events = … try { events.forEach(e -> onNextEvent(e)); onSuccessfulComplete(); } catch (Throwable t) { onErrorEvent(t); }
  • 118. // Stream<Event> stream = … try { stream .map(e -> transform(e)) // more transformations
 .forEach(e -> onNextEvent(e)); onSuccessfulComplete(); } catch (Throwable t) { onErrorEvent(t); }
  • 119. // Observable<Event> observable = … observable .map(e -> transform(e)) // more transformations
 .subscribe( e -> onNextEvent(e), t -> onSuccessfulComplete(), () -> onErrorEvent(t) );
  • 120.
  • 121.
  • 122. // input expressed as: ‘a’, ‘b’, ‘c’ Output hardWork(Input in) { log("Beginning Work: " + in.id()); // Very HARD WORK such as Network I/O log("Done Work: " + in.id()); return out; }
  • 123. log("start") observable.map(x -> hardWork(x)) .filter(x -> f(x)) .operator(x -> g(x)) ... .subscribe(x -> log("result: " + x); log("end");
  • 124.
  • 125.
  • 126. log("start") observable.map(x -> hardWork(x)) .filter(x -> f(x)) .operator(x -> g(x)) .subscribeOn(scheduler) ... .subscribe(x -> log("result: " + x); log("end");
  • 127.
  • 128.
  • 129. log("start") observable .flatMap(x -> Observable.fromCallable(() -> hardWork(x)) .subscribeOn(scheduler) ) .filter(x -> f(x)) .operator(x -> g(x)) ... .subscribe(x -> log("result: " + x); log("end");
  • 130. log("start") observable .flatMap(x -> Observable.defer(() -> Observable.just(hardWork(x)) ).subscribeOn(scheduler) ) .filter(x -> f(x)) .operator(x -> g(x)) ... .subscribe(x -> log("result: " + x); log("end");
  • 131.
  • 132.
  • 133.
  • 134. log("prepare"); Observable<Long> a = Observable.just("bread") .doOnNext(x -> log("substream: " + x)) .map(x -> repository.purchase(x, 1)) .subscribeOn(schedulerA()); Observable<Long> b = Observable.just("cucumber") .doOnNext(x -> log("substream: " + x)) .map(x -> repository.purchase(x, 3)) .subscribeOn(schedulerA()); Observable<Long> c = Observable.just("beef") .doOnNext(x -> log("substream: " + x)) .map(x -> repository.purchase(x, 5)) .subscribeOn(schedulerA()); log("start"); Observable.just(a, b, c) .flatMap(x -> x) .observeOn(schedulerB()) // .reduce((x, y) -> x.add(y)) .subscribe(x -> log("Q'ty: " + x)); log("end");
  • 135.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141. destination.path("recommended").request().header("Rx-User", "Async").async() .get(new InvocationCallback<List<Destination>>() { public void completed(final List<Destination> recommended) { final CountDownLatch innerLatch = new CountDownLatch(recommended.size()); final Map<String, Forecast> forecasts = Collections.synchronizedMap(new HashMap<>()); for (final Destination dest : recommended) { forecast.resolveTemplate("destination", dest.getDestination()).request().async() .get(new InvocationCallback<Forecast>() { public void completed(final Forecast forecast) { forecasts.put(dest.getDestination(), forecast); innerLatch.countDown(); } public void failed(final Throwable throwable) { errors.offer("Forecast: " + throwable.getMessage()); innerLatch.countDown(); } }); } try { if (!innerLatch.await(10, TimeUnit.SECONDS)) errors.offer("Inner: Waiting for requests to complete has timed out."); } catch (final InterruptedException e) { errors.offer("Inner: Waiting for requests to complete has been interrupted."); } // Continue with processing. } public void failed(final Throwable throwable) { errors.offer("Recommended: " + throwable.getMessage()); } });
  • 142.
  • 143.
  • 144.
  • 145. Observable<Destination> recommended = RxObservable.from(dest) .path("recommended") .request() .header("Rx-User", "RxJava") .rx().get(new GenericType<List<Destination>>() {}) .onErrorReturn(t -> emptyList()) .flatMap(Observable::from) .cache(); Observable<Forecast> forecasts = recommended.flatMap(dest -> RxObservable.from(forecast) .resolveTemplate("destination", dest.getDestination()) .request().rx().get(Forecast.class) .onErrorReturn(t -> new Forecast(dest.getDestination(), "N/A") ) ); Observable<Recommendation> recommendations = Observable.zip( recommended, forecasts, Recommendation::new);
  • 146.
  • 147.
  • 148. Existing Structure (SpringCamp 2016) user
 service 40+ tables admin
 console client slave
 (MySQL)master
 (MySQL) adjustment C/R/U/D update “list” order fetch “list” 10+ RPCs
  • 149.
  • 150. C/R/U/D replicator40+ tables admin
 console composite json master
 (MySQL) item data adjustment purchase data #1 #2 Asymmetric Replication (SpringCamp 2016) user
 service NoSQL replica
 (Couchbase) client
  • 151.
  • 152. List<FixedDeal> fixed = fixedDealService.find(cid, bid); FixedDealPagination pagination = FixedDealPagination.paginate(fixed, limit); FixedDealPage currentPage = pagination.find(pageNo); PaginationOffset offset = PaginationOffset.adjust(currentPage); List<String> plain = plainDealService.find(cid, bid, offset); List<String> collatedIds = PageRankCollator.collate(currentPage, plain) return Observable.from(collatedIds) .concatMapEager(repository::get) .map(JsonDocument::content) .map(stickerFilter::apply) .map(priceFilter::apply) .map(viewAttributeFilter::apply) .toList() .toBlocking() .singleOrDefault(Json.DEAL_LIST_DEFAULT);
  • 153.
  • 154. Observable<FixedDeal> fixed = fixedDealService.prepare(cid, bid, pageNo, limit); Observable<PlainDeal> plain = plainDealService.prepare(cid, bid, pageNo, limit); return Observable.zip(fixed, plain, DealId::collate) .flatMap(DealId::targets) .concatMapEager(repository::get) .map(JsonDocument::content) .map(stickerFilter::apply) .map(priceFilter::apply) .map(viewAttributeFilter::apply) .toList() .toBlocking() .singleOrDefault(Json.DEAL_LIST_DEFAULT);
  • 155.
  • 156. // 1. gather from N tables concurrently, then aggregate // 2. insert to replica persistence Observable<Deal> deal = Observable.just(dealNo) .flatMap(id -> dealRepository.findDeferred(id)) .retry(3) .onErrorReturn(throwable -> Deal.ERROR); Observable<DealCategory> category = Observable.just(categoryNo) .flatMap(id -> dealCategoryRepository.findDeferred(id)) .retry(3) .onErrorReturn(throwable -> DealCategory.ERROR); Observable<DealScore> score = Observable.just(dealNo) .flatMap(id -> dealScoreRepository.findDeferred(id)) .onErrorReturn(throwable -> DealScore.DEFAULT); Observable.zip(deal, category, score, DealJson::aggregate) .observeOn(schedulerSlot.dealSourceScheduler()) .subscribe(src -> replicaService.send(src));