Search code examples
rx-javarx-java2

RxJava - Casting a List to a generic Collection


What is the correct way to create a generic collection using RxJava? If I do the following, I get a type mismatch because it returns a Single<List<MyObj>>. I have also tried flatMapSingle() and collect(), but I'm not sure how to give it the correct types.

public Single<Collection<MyObj>> someMethod() {
  Observable<Collection<MyObj>> someObservable = getData();
  return someObservable 
         .flatMapIterable(item -> item)
         .filter(someFilter)
         .toList();
}

Solution

  • Unfortunately, Java doesn't have co- and contravariance like other languages have, thus Observable<List<T>> can't be assigned to Observable<Collection<T>>. You have to upcast the value type manually:

    public Single<Collection<MyObj>> someMethod() {
        Observable<Collection<MyObj>> someObservable = getData();
        return someObservable 
               .flatMapIterable(item -> item)
               .filter(someFilter)
               .toList()
               .map(list -> (Collection<MyObj>)list);
    }