-
Notifications
You must be signed in to change notification settings - Fork 7.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Simple Scheduler Question #3062
Comments
Here's one way using final CountDownLatch latch = new CountDownLatch(1);
Observable.just(1, 2, 3, 4, 5).subscribeOn(Schedulers.io())
.subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
latch.countDown();
}
@Override
public void onNext(Integer integer) {
System.out.println("onNext: " + integer);
}
});
latch.await(); and another way (which uses Observable.just(1, 2, 3, 4, 5).subscribeOn(Schedulers.io())
.doOnNext(n -> System.out.println("onNext: " + n))
.doOnCompleted(() -> System.out.println("onCompleted"))
.doOnError(e -> e.printStackTrace())
.count().toBlocking().single(); |
If you don't have java 8 at your disposal this might be convenient: Observable.just(1, 2, 3, 4, 5).subscribeOn(Schedulers.io())
.doOnEach(new Observer<Integer>() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(Integer integer) {
System.out.println("onNext: " + integer);
}
}).count().toBlocking().single(); |
I appreciate the alternative approaches, but can you tell me why my original code doesn't work? You changed several operators and introduced new external things (latch). How/why did you get to those alternatives from the original? Thanks. |
The effect of
So the catch here is you are trying to observe on the main thread. If rather you were trying to observe on a non-current-thread scheduler (not |
Ok, that's starting to help a bit. Would my code work if my observable was something (anything) more time intensive than static data? Reading a byte from disk, for example? Is it a race condition issue of sorts? |
No, wouldn't help because as soon as you call |
Oh! Thank you, that's what I was missing. I think it just clicked. I appreciate your help. 👍 |
Trying to get started with RxJava and my very first attempt is failing. Can someone explain to me why the following code does not print anything out? If I remove the
.subscribeOn(...)
, it works fine, but the goal here was to simulate subscribing to some long-running task on the IO thread and observing it back on the main thread. I tried adding an.observeOn(Schedulers.immediate())
, but it didn't seem to matter if I included it or not.Can someone point me in the right direction, please? Thanks.
The text was updated successfully, but these errors were encountered: