forked from reactive-streams/reactive-streams-jvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfiniteIncrementNumberPublisher.java
52 lines (38 loc) · 1.45 KB
/
InfiniteIncrementNumberPublisher.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
package org.reactivestreams.example.unicast;
import java.util.concurrent.atomic.AtomicInteger;
import org.reactivestreams.Subscription;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Publisher;
class InfiniteIncrementNumberPublisher implements Publisher<Integer> {
@Override
public void subscribe(final Subscriber<Integer> s) {
final AtomicInteger i = new AtomicInteger();
Subscription subscription = new Subscription() {
AtomicInteger capacity = new AtomicInteger();
@Override
public void request(long n) {
System.out.println("signalAdditionalDemand => " + n);
if (capacity.getAndAdd(n) == 0) {
// start sending again if it wasn't already running
send();
}
}
private void send() {
System.out.println("send => " + capacity.get());
// this would normally use an eventloop, actor, whatever
new Thread(new Runnable() {
public void run() {
do {
s.onNext(i.incrementAndGet());
} while (capacity.decrementAndGet() > 0);
}
}).start();
}
@Override
public void cancel() {
capacity.set(-1);
}
};
s.onSubscribe(subscription);
}
}