Skip to content

Commit df66270

Browse files
don't throw exception on iterator.hasNext()
1 parent 4f8778e commit df66270

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

rxjava-core/src/main/java/rx/operators/OperationNext.java

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,12 +70,12 @@ private NextIterator(NextObserver<T> observer) {
7070

7171
@Override
7272
public boolean hasNext() {
73-
return !observer.isCompleted();
73+
return !observer.isCompleted(false);
7474
}
7575

7676
@Override
7777
public T next() {
78-
if (observer.isCompleted()) {
78+
if (observer.isCompleted(true)) {
7979
throw new IllegalStateException("Observable is completed");
8080
}
8181

@@ -131,14 +131,18 @@ public void await() {
131131
waiting.set(true);
132132
}
133133

134-
public boolean isCompleted() {
134+
public boolean isCompleted(boolean rethrowExceptionIfExists) {
135135
Notification<T> lastItem = buf.peek();
136136
if (lastItem == null) {
137137
return false;
138138
}
139139

140140
if (lastItem.isOnError()) {
141-
throw Exceptions.propagate(lastItem.getException());
141+
if (rethrowExceptionIfExists) {
142+
throw Exceptions.propagate(lastItem.getException());
143+
} else {
144+
return true;
145+
}
142146
}
143147

144148
return lastItem.isOnCompleted();
@@ -219,6 +223,35 @@ public void testOnError() throws Throwable {
219223
}
220224
}
221225

226+
@Test
227+
public void testOnErrorViaHasNext() throws Throwable {
228+
Subscription s = mock(Subscription.class);
229+
final TestObservable obs = new TestObservable(s);
230+
231+
Iterator<String> it = next(obs).iterator();
232+
233+
assertTrue(it.hasNext());
234+
235+
Future<String> next = nextAsync(it);
236+
Thread.sleep(100);
237+
obs.sendOnNext("one");
238+
assertEquals("one", next.get());
239+
240+
assertTrue(it.hasNext());
241+
242+
next = nextAsync(it);
243+
Thread.sleep(100);
244+
obs.sendOnError(new TestException());
245+
246+
// this should not throw an exception but instead just return false
247+
try {
248+
assertFalse(it.hasNext());
249+
} catch (Exception e) {
250+
fail("should not have received exception");
251+
e.printStackTrace();
252+
}
253+
}
254+
222255
private Future<String> nextAsync(final Iterator<String> it) throws Exception {
223256

224257
return executor.submit(new Callable<String>() {
@@ -250,7 +283,6 @@ public void sendOnNext(String value) {
250283
}
251284

252285
/* used to simulate subscription */
253-
@SuppressWarnings("unused")
254286
public void sendOnError(Exception e) {
255287
observer.onError(e);
256288
}

0 commit comments

Comments
 (0)