Skip to content

Subscriber.request should throw exception if negative request made #2548

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

Merged
merged 1 commit into from
Jan 28, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/main/java/rx/Subscriber.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,13 @@ public void onStart() {
*
* @param n the maximum number of items you want the Observable to emit to the Subscriber at this time, or
* {@code Long.MAX_VALUE} if you want the Observable to emit items at its own pace
* @throws IllegalArgumentException
* if {@code n} is negative
*/
protected final void request(long n) {
if (n < 0) {
throw new IllegalArgumentException("number requested cannot be negative: " + n);
}
Producer shouldRequest = null;
synchronized (this) {
if (p != null) {
Expand Down
35 changes: 35 additions & 0 deletions src/test/java/rx/SubscriberTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,13 @@
package rx;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

import org.junit.Test;

Expand Down Expand Up @@ -419,4 +423,35 @@ public void onNext(Integer t) {

assertEquals(1, c.get());
}

@Test
public void testNegativeRequestThrowsIllegalArgumentException() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
Observable.just(1,2,3,4).subscribe(new Subscriber<Integer>() {

@Override
public void onStart() {
request(1);
}

@Override
public void onCompleted() {

}

@Override
public void onError(Throwable e) {
exception.set(e);
latch.countDown();
}

@Override
public void onNext(Integer t) {
request(-1);
request(1);
}});
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertTrue(exception.get() instanceof IllegalArgumentException);
}
}