-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathObservableVSIterator.java
76 lines (61 loc) · 1.72 KB
/
ObservableVSIterator.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
package com.packtpub.reactive.chapter01;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;
import com.packtpub.reactive.common.Program;
/**
* Demonstrate the differences between Iterators and Observables.
*
* @author meddle
*/
public class ObservableVSIterator implements Program {
private static void usingIteratorExample() {
List<String> list = Arrays
.asList("One", "Two", "Three", "Four", "Five");
Iterator<String> iterator = list.iterator();
// While there is a next element, PULL it from the source and print it.
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
private static void usingObservableExample() {
List<String> list = Arrays
.asList("One", "Two", "Three", "Four", "Five");
Observable<String> observable = Observable.from(list);
// Subscribe to the Observable. It will PUSH it's values to the Subscriber, and it will be printed.
observable.subscribe(new Action1<String>() {
public void call(String element) {
System.out.println(element);
}
}, new Action1<Throwable>() {
public void call(Throwable t) {
System.err.println(t); // (1)
}
}, new Action0() {
public void call() {
System.out.println("We've finnished!"); // (2)
}
});
}
@Override
public String name() {
return "Iterator vs Observable";
}
@Override
public void run() {
System.out.println("Running Iterator example:");
usingIteratorExample();
System.out.println("Running Observable example:");
usingObservableExample();
}
@Override
public int chapter() {
return 1;
}
public static void main(String[] args) {
new ObservableVSIterator().run();
}
}