-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathSubjectsDemonstration.java
81 lines (58 loc) · 1.65 KB
/
SubjectsDemonstration.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
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.subjects.PublishSubject;
import rx.subjects.Subject;
import com.packtpub.reactive.common.Program;
/**
* Demonstration of using Subjects and what we could do with them.
* Uses a {@link PublishSubject} to subscribe to an {@link Observable} and propagate its notifications.
*
* @author meddle
*/
public class SubjectsDemonstration implements Program {
@Override
public String name() {
return "Subjects demonstration";
}
@Override
public int chapter() {
return 3;
}
@Override
public void run() {
Observable<Long> interval = Observable.interval(100L,
TimeUnit.MILLISECONDS);
Subject<Long, Long> publishSubject = PublishSubject.create();
interval.subscribe(publishSubject);
Subscription sub1 = subscribePrint(publishSubject, "First");
Subscription sub2 = subscribePrint(publishSubject, "Second");
Subscription sub3 = null;
try {
Thread.sleep(300L);
publishSubject.onNext(555L);
sub3 = subscribePrint(publishSubject, "Third");
Thread.sleep(500L);
} catch (InterruptedException e) {
}
sub1.unsubscribe();
sub2.unsubscribe();
sub3.unsubscribe();
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
}
Subscription sub4 = subscribePrint(publishSubject, "Fourth");
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
}
sub4.unsubscribe();
System.out.println("-----------------------------");
}
public static void main(String[] args) {
new SubjectsDemonstration().run();
}
}