-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathCh8_08.java
More file actions
63 lines (54 loc) · 2.13 KB
/
Copy pathCh8_08.java
File metadata and controls
63 lines (54 loc) · 2.13 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
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
public class Ch8_08 {
public static void main(String[] args) {
Flowable.range(1, 1000)
.doOnNext(s -> System.out.println("Source pushed " + s))
.observeOn(Schedulers.io())
.map(i -> intenseCalculation(i))
.subscribe(new Subscriber<Integer>() {
Subscription subscription;
AtomicInteger count = new AtomicInteger(0);
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
System.out.println("Requesting 40 items!");
subscription.request(40);
}
@Override
public void onNext(Integer s) {
sleep(50);
System.out.println("Subscriber received " + s);
if (count.incrementAndGet() % 20 == 0 && count.get() >= 40) {
System.out.println("Requesting 20 more !");
subscription.request(20);
}
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onComplete() {
System.out.println("Done!");
}
});
sleep(20000);
}
public static <T> T intenseCalculation(T value) {
//sleep up to 200 milliseconds
sleep(ThreadLocalRandom.current().nextInt(200));
return value;
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}