-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathParallelRequestsExample.java
More file actions
75 lines (58 loc) · 1.75 KB
/
ParallelRequestsExample.java
File metadata and controls
75 lines (58 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.packtpub.reactive.chapter06;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import rx.Observable;
import rx.schedulers.Schedulers;
import com.packtpub.reactive.common.CreateObservable;
import com.packtpub.reactive.common.Program;
/**
* Demonstrates parallelism by executing a number of requests in parallel.
*
* @author meddle
*/
public class ParallelRequestsExample implements Program {
@Override
public String name() {
return "Demonstraton of parallelism";
}
@Override
public int chapter() {
return 6;
}
@SuppressWarnings("rawtypes")
@Override
public void run() {
CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
CountDownLatch latch = new CountDownLatch(1);
try {
client.start();
Observable<Map> response = CreateObservable.requestJson(client, "https://api.github.com/users/meddle0x53/followers");
response
.map(followerJson -> followerJson.get("url"))
.cast(String.class)
.flatMap(profileUrl -> CreateObservable
.requestJson(client, profileUrl)
.subscribeOn(Schedulers.io())
.filter(res -> res.containsKey("followers"))
.map(json -> json.get("login") + " : " + json.get("followers"))
)
.doOnNext(follower -> System.out.println(follower))
.count()
.doOnCompleted(() -> latch.countDown())
.subscribe(sum -> System.out.println("meddle0x53 : " + sum));
try {
latch.await();
} catch (InterruptedException e) {}
} finally {
try {
client.close();
} catch (IOException e) {}
}
}
public static void main(String[] args) {
new ParallelRequestsExample().run();
}
}