Given a class Foo
and a class Bar extends Foo
, it seems as though it should be safe to cast an Observable<Bar>
to an Observable<Foo>
— Observables
are read-only, aren't they? But there doesn't seem to be any out-of-the box way to do it without warnings, other than something like
Observable<Bar> barObservable = ...
Observable<Foo> fooObservable = barObservable.map(Foo.class::cast);
// or: Observable<Foo> fooObservable = barObservable.cast(Foo.class);
which compiles without errors, but seems as though it will incur extra method call overhead unless the compiler is very clever.
Other libraries like vavr.io have built-in narrow()
methods that at least suppress the warning for you, the equivalent of:
@SuppressWarnings("unchecked")
public static <T> Observable<T> narrow(Observable<? extends T> o) {
return (Observable<T>) o;
}
But RxJava2 doesn't seem to provide such methods, which makes me wonder if I'm missing something and it's not as safe as I think.
ETA: As (relatively) clean as map(Foo.class::cast)
/ cast(Foo.class)
looks, I've realized it's preferable to write
barObservable.map(b -> (Foo) b);
as this will give you a compilation error if Bar
cannot be cast to Foo
.
(It won't help with generics, though; you'll just get an unsafe cast warning. For generics, the custom narrow()
implementation above seems more type-safe.)