I'm learning about RxJava operator, and I found these code below did not print anything:
public static void main(String[] args) {
Observable
.interval(1, TimeUnit.SECONDS)
.subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println("onError -> " + e.getMessage());
}
@Override
public void onNext(Long l) {
System.out.println("onNext -> " + l);
}
});
}
As ReactiveX, interval
create an Observable that emits a sequence of integers spaced by a particular time interval
Did I make a mistake or forget about something?
Interval Method (TimeSpan) Returns an observable sequence that produces a value after each period.
onNext(): This method is called when a new item is emitted from the Observable. onError(): This method is called when an error occurs and the emission of data is not successfully completed. onComplete(): This method is called when the Observable has successfully completed emitting all items.
Single and Completable are new types introduced exclusively at RxJava that represent reduced types of Observable , that have more concise API. Single represent Observable that emit single value or error. Completable represent Observable that emits no value, but only terminal events, either onError or onCompleted.
You have to block until the observable is consumed:
public static void main(String[] args) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
Observable
.interval(1, TimeUnit.SECONDS)
.subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
// make sure to complete only when observable is done
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println("onError -> " + e.getMessage());
}
@Override
public void onNext(Long l) {
System.out.println("onNext -> " + l);
}
});
// wait for observable to complete (never in this case...)
latch.await();
}
You can add .take(10)
for example to see the observable complete.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With