Skip to content

Commit cde7449

Browse files
committed
Implemented the 'ofType' operator
1 parent 6788900 commit cde7449

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

rxjava-core/src/main/java/rx/Observable.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4350,6 +4350,27 @@ public <R> Observable<R> cast(final Class<R> klass) {
43504350
return create(OperationCast.cast(this, klass));
43514351
}
43524352

4353+
/**
4354+
* Filters the elements of an observable sequence based on the specified
4355+
* type.
4356+
*
4357+
* @param klass
4358+
* The class type to filter the elements in the source sequence
4359+
* on.
4360+
*
4361+
* @return An observable sequence that contains elements from the input
4362+
* sequence of type klass.
4363+
*
4364+
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229380(v=vs.103).aspx">MSDN: Observable.OfType</a>
4365+
*/
4366+
public <R> Observable<R> ofType(final Class<R> klass) {
4367+
return filter(new Func1<T, Boolean>() {
4368+
public Boolean call(T t) {
4369+
return klass.isAssignableFrom(t.getClass());
4370+
}
4371+
}).cast(klass);
4372+
}
4373+
43534374
/**
43544375
* Whether a given {@link Function} is an internal implementation inside rx.* packages or not.
43554376
* <p>

rxjava-core/src/test/java/rx/ObservableTests.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -701,4 +701,21 @@ public void onNext(String v) {
701701
fail("It should be a NumberFormatException");
702702
}
703703
}
704+
705+
@Test
706+
public void testOfType() {
707+
Observable<String> observable = Observable.from(1, "abc", false, 2L).ofType(String.class);
708+
709+
@SuppressWarnings("unchecked")
710+
Observer<Object> aObserver = mock(Observer.class);
711+
observable.subscribe(aObserver);
712+
verify(aObserver, never()).onNext(1);
713+
verify(aObserver, times(1)).onNext("abc");
714+
verify(aObserver, never()).onNext(false);
715+
verify(aObserver, never()).onNext(2L);
716+
verify(aObserver, never()).onError(
717+
org.mockito.Matchers.any(Throwable.class));
718+
verify(aObserver, times(1)).onCompleted();
719+
}
720+
704721
}

0 commit comments

Comments
 (0)