-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathCh6_15.java
More file actions
56 lines (52 loc) · 1.99 KB
/
Copy pathCh6_15.java
File metadata and controls
56 lines (52 loc) · 1.99 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
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class Ch6_15 {
public static void main(String[] args) {
//Happens on IO Scheduler
Observable.just("WHISKEY/27653/TANGO", "6555/BRAVO",
"232352/5675675/FOXTROT")
.subscribeOn(Schedulers.io())
.flatMap(s -> Observable.fromArray(s.split("/")))
.doOnNext(s -> System.out.println("Split out " + s +
" on thread " + Thread.currentThread().getName()))
//Happens on Computation Scheduler
.observeOn(Schedulers.computation())
.filter(s -> s.matches("[0-9]+"))
.map(Integer::valueOf)
.reduce((total, next) -> total + next)
.doOnSuccess(i -> System.out.println("Calculated sum" + i +
" on thread " + Thread.currentThread().getName()))
//Switch back to IO Scheduler
.observeOn(Schedulers.io())
.map(i -> i.toString())
.doOnSuccess(s -> System.out.println("Writing " + s +
" to file on thread " + Thread.currentThread().getName()))
.subscribe(s -> write(s, "/home/thomas/Desktop/output.txt"));
sleep(1000);
}
public static void write(String text, String path) {
BufferedWriter writer = null;
try {
//create a temporary file
File file = new File(path);
writer = new BufferedWriter(new FileWriter(file));
writer.append(text);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {}
}
}
private static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}