-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathResourceManagement.java
90 lines (69 loc) · 2.35 KB
/
ResourceManagement.java
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.packtpub.reactive.chapter08;
import java.io.IOException;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.client.HttpAsyncClient;
import rx.Observable;
import rx.apache.http.ObservableHttp;
import rx.apache.http.ObservableHttpResponse;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import com.packtpub.reactive.common.Program;
/**
* Demonstration of custom resource management with {@link Observable#using}.
*
* @author meddle
*/
public class ResourceManagement implements Program {
@Override
public String name() {
return "Resource management demonstration";
}
@Override
public int chapter() {
return 8;
}
public Observable<ObservableHttpResponse> request(String url) {
Func0<CloseableHttpAsyncClient> resourceFactory = () -> {
CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
System.out.println(Thread.currentThread().getName() + " : Created and started the client.");
return client;
};
Func1<HttpAsyncClient, Observable<ObservableHttpResponse>> observableFactory = (client) -> {
System.out.println(Thread.currentThread().getName() + " : About to create Observable.");
return ObservableHttp.createGet(url, client).toObservable();
};
Action1<CloseableHttpAsyncClient> disposeAction = (client) -> {
try {
System.out.println(Thread.currentThread().getName() + " : Closing the client.");
client.close();
} catch (IOException e) {
}
};
return Observable.using(
resourceFactory,
observableFactory,
disposeAction);
}
@Override
public void run() {
String url = "https://api.github.com/orgs/ReactiveX/repos";
Observable<ObservableHttpResponse> response = request(url);
System.out.println("Not yet subscribed.");
Observable<String> stringResponse = response
.<String>flatMap(resp -> resp.getContent()
.map(bytes -> new String(bytes, java.nio.charset.StandardCharsets.UTF_8)))
.retry(5)
.map(String::trim)
.cache();
System.out.println("Subscribe 1:");
System.out.println(stringResponse.toBlocking().first());
System.out.println("Subscribe 2:");
System.out.println(stringResponse.toBlocking().first());
}
public static void main(String[] args) {
new ResourceManagement().run();
}
}