Skip to content

Commit 4182f65

Browse files
committed
Merge pull request #2622 from akarnokd/EmptyObservable
Changed Observable.empty() into a stateless constant observable.
2 parents dc60f00 + 8982110 commit 4182f65

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

src/main/java/rx/Observable.java

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,11 @@
1515
import java.util.*;
1616
import java.util.concurrent.*;
1717

18-
import rx.annotations.Beta;
19-
import rx.annotations.Experimental;
18+
import rx.annotations.*;
2019
import rx.exceptions.*;
2120
import rx.functions.*;
2221
import rx.internal.operators.*;
23-
import rx.internal.util.ScalarSynchronousObservable;
24-
import rx.internal.util.UtilityFunctions;
22+
import rx.internal.util.*;
2523
import rx.observables.*;
2624
import rx.observers.SafeSubscriber;
2725
import rx.plugins.*;
@@ -1031,6 +1029,14 @@ public final static <T> Observable<T> defer(Func0<Observable<T>> observableFacto
10311029
return create(new OnSubscribeDefer<T>(observableFactory));
10321030
}
10331031

1032+
/** An empty observable which just emits onCompleted to any subscriber. */
1033+
private static final Observable<Object> EMPTY = create(new OnSubscribe<Object>() {
1034+
@Override
1035+
public void call(Subscriber<? super Object> t1) {
1036+
t1.onCompleted();
1037+
}
1038+
});
1039+
10341040
/**
10351041
* Returns an Observable that emits no items to the {@link Observer} and immediately invokes its
10361042
* {@link Observer#onCompleted onCompleted} method.
@@ -1047,8 +1053,9 @@ public final static <T> Observable<T> defer(Func0<Observable<T>> observableFacto
10471053
* {@link Observer}'s {@link Observer#onCompleted() onCompleted} method
10481054
* @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Empty</a>
10491055
*/
1056+
@SuppressWarnings("unchecked")
10501057
public final static <T> Observable<T> empty() {
1051-
return from(Collections.<T>emptyList());
1058+
return (Observable<T>)EMPTY;
10521059
}
10531060

10541061
/**

src/test/java/rx/ObservableTests.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1116,4 +1116,17 @@ public void testErrorThrownIssue1685() {
11161116
System.out.println("Done");
11171117
}
11181118

1119+
@Test
1120+
public void testEmptyIdentity() {
1121+
assertEquals(Observable.empty(), Observable.empty());
1122+
}
1123+
1124+
@Test
1125+
public void testEmptyIsEmpty() {
1126+
Observable.<Integer>empty().subscribe(w);
1127+
1128+
verify(w).onCompleted();
1129+
verify(w, never()).onNext(any(Integer.class));
1130+
verify(w, never()).onError(any(Throwable.class));
1131+
}
11191132
}

0 commit comments

Comments
 (0)