From 1c29e7c9b4d0f9ecfa3e69f294a0b2924db54cae Mon Sep 17 00:00:00 2001 From: Dave Moten Date: Tue, 21 Apr 2015 10:00:32 +1000 Subject: [PATCH] Observable.from(iterable) should emit onCompleted even if none requested when iterable is empty --- .../operators/OnSubscribeFromIterable.java | 5 ++- .../OnSubscribeFromIterableTest.java | 31 +++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/main/java/rx/internal/operators/OnSubscribeFromIterable.java b/src/main/java/rx/internal/operators/OnSubscribeFromIterable.java index e4589a4f57..766b624416 100644 --- a/src/main/java/rx/internal/operators/OnSubscribeFromIterable.java +++ b/src/main/java/rx/internal/operators/OnSubscribeFromIterable.java @@ -44,7 +44,10 @@ public OnSubscribeFromIterable(Iterable iterable) { @Override public void call(final Subscriber o) { final Iterator it = is.iterator(); - o.setProducer(new IterableProducer(o, it)); + if (!it.hasNext() && !o.isUnsubscribed()) + o.onCompleted(); + else + o.setProducer(new IterableProducer(o, it)); } private static final class IterableProducer implements Producer { diff --git a/src/test/java/rx/internal/operators/OnSubscribeFromIterableTest.java b/src/test/java/rx/internal/operators/OnSubscribeFromIterableTest.java index b9f829783a..91bf65bf4d 100644 --- a/src/test/java/rx/internal/operators/OnSubscribeFromIterableTest.java +++ b/src/test/java/rx/internal/operators/OnSubscribeFromIterableTest.java @@ -27,6 +27,7 @@ import java.util.Iterator; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import org.mockito.Mockito; @@ -74,12 +75,12 @@ public Iterator iterator() { @Override public boolean hasNext() { - return i++ < 3; + return i < 3; } @Override public String next() { - return String.valueOf(i); + return String.valueOf(++i); } @Override @@ -193,5 +194,31 @@ public void onNext(Integer t) { assertTrue(latch.await(10, TimeUnit.SECONDS)); } + @Test + public void testFromEmptyIterableWhenZeroRequestedShouldStillEmitOnCompletedEagerly() { + final AtomicBoolean completed = new AtomicBoolean(false); + Observable.from(Collections.emptyList()).subscribe(new Subscriber() { + + @Override + public void onStart() { + request(0); + } + + @Override + public void onCompleted() { + completed.set(true); + } + @Override + public void onError(Throwable e) { + + } + + @Override + public void onNext(Object t) { + + }}); + assertTrue(completed.get()); + } + }