Skip to content

Commit 997546f

Browse files
Fix behavior of BlockingObservable.last
It now throws an IllegalArgumentException instead of returning null if no elements are emitted. This is based on feedback from @headinthebox confirming this expected behavior: var xs = Observable.Range(1,0); // empty sequence int x = xs.Last().Dump(); // throws “sequence contains no elements” RxJava => BlockingObservable.last() IObservable<int> ys = xs.TakeLast(1).Dump(); // OnCompleted() RxJava => Observable.takeLast(1) IObservable<int> zs = xs.LastAsync().Dump(); // OnError(“sequence contains no elements”) RxJava => Observable.last()
1 parent 11af5d6 commit 997546f

File tree

2 files changed

+4
-8
lines changed

2 files changed

+4
-8
lines changed

rxjava-core/src/main/java/rx/observables/BlockingObservable.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -178,13 +178,10 @@ public Iterator<T> getIterator() {
178178
* <img width="640" src="https://github.com/Netflix/RxJava/wiki/images/rx-operators/B.last.png">
179179
*
180180
* @return the last item emitted by the source {@link Observable}
181+
* @throws IllegalArgumentException if source contains no elements
181182
*/
182183
public T last() {
183-
T result = null;
184-
for (T value : toIterable()) {
185-
result = value;
186-
}
187-
return result;
184+
return new BlockingObservable<T>(o.last()).single();
188185
}
189186

190187
/**

rxjava-core/src/test/java/rx/observables/BlockingObservableTest.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,10 @@ public void testLast() {
4949
assertEquals("three", obs.last());
5050
}
5151

52-
@Test
52+
@Test(expected = IllegalArgumentException.class)
5353
public void testLastEmptyObservable() {
5454
BlockingObservable<Object> obs = BlockingObservable.from(Observable.empty());
55-
56-
assertNull(obs.last());
55+
obs.last();
5756
}
5857

5958
@Test

0 commit comments

Comments
 (0)