-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathUsingConnectableObservables.java
More file actions
86 lines (64 loc) · 1.8 KB
/
UsingConnectableObservables.java
File metadata and controls
86 lines (64 loc) · 1.8 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
76
77
78
79
80
81
82
83
84
85
86
package com.packtpub.reactive.chapter03;
import static com.packtpub.reactive.common.Helpers.subscribePrint;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Subscription;
import rx.observables.ConnectableObservable;
import com.packtpub.reactive.common.Program;
/**
* Demonstrates how to create and use ConnectableObservables.
*
* @author meddle
*/
public class UsingConnectableObservables implements Program {
@Override
public String name() {
return "A ConnectableObservable demonstration";
}
@Override
public int chapter() {
return 3;
}
@Override
public void run() {
Observable<Long> interval = Observable.interval(100L,
TimeUnit.MILLISECONDS);
ConnectableObservable<Long> published = interval.publish();
Subscription sub1 = subscribePrint(published, "First");
Subscription sub2 = subscribePrint(published, "Second");
published.connect();
Subscription sub3 = null;
try {
Thread.sleep(300L);
sub3 = subscribePrint(published, "Third");
Thread.sleep(500L);
} catch (InterruptedException e) {
}
sub1.unsubscribe();
sub2.unsubscribe();
sub3.unsubscribe();
System.out.println("-----------------------------------");
Observable<Long> refCount = interval.share(); // publish().refCount();
sub1 = subscribePrint(refCount, "First");
sub2 = subscribePrint(refCount, "Second");
sub3 = null;
try {
Thread.sleep(300L);
sub3 = subscribePrint(refCount, "Third");
Thread.sleep(500L);
} catch (InterruptedException e) {
}
sub1.unsubscribe();
sub2.unsubscribe();
sub3.unsubscribe();
Subscription sub4 = subscribePrint(refCount, "Fourth");
try {
Thread.sleep(300L);
} catch (InterruptedException e) {
}
sub4.unsubscribe();
}
public static void main(String[] args) {
new UsingConnectableObservables().run();
}
}