Last active
August 29, 2015 14:04
-
-
Save benjchristensen/60b1b301411612a099a3 to your computer and use it in GitHub Desktop.
ThrottleExample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
0 | |
11 | |
20 | |
30 | |
43 | |
53 | |
64 | |
74 | |
83 | |
93 | |
8 | |
16 | |
25 | |
38 | |
49 | |
60 | |
67 | |
76 | |
88 | |
98 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.TimeUnit; | |
import rx.Observable; | |
import rx.Subscriber; | |
import rx.schedulers.Schedulers; | |
public class ThrottleExample { | |
public static void main(String args[]) { | |
// first item emitted in each time window | |
hotStream().throttleFirst(500, TimeUnit.MILLISECONDS).take(10).toBlocking().forEach(System.out::println); | |
// last item emitted in each time window | |
hotStream().throttleLast(500, TimeUnit.MILLISECONDS).take(10).toBlocking().forEach(System.out::println); | |
} | |
/** | |
* This is an artificial source to demonstrate an infinite stream that emits randomly | |
*/ | |
public static Observable<Integer> hotStream() { | |
return Observable.create((Subscriber<? super Integer> s) -> { | |
int i = 0; | |
while (!s.isUnsubscribed()) { | |
s.onNext(i++); | |
try { | |
// sleep for a random amount of time | |
// NOTE: Only using Thread.sleep here as an artificial demo. | |
Thread.sleep((long) (Math.random() * 100)); | |
} catch (Exception e) { | |
// do nothing | |
} | |
} | |
}).subscribeOn(Schedulers.newThread()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment