Sergio Vargas
Sergio Vargas

Reputation: 93

Return Final List from Filtered Observable

I have an

Observable<List<ObjectModel>>

and I need the list returned to be Immutable, however for some reason when applying the below filter it is not. Can someone tell me how to preserve Immutability? thanks!

observable.subscribeOn(Schedulers.io())
                .flatMap(Observable::from).filter(objectModel -> {
                return objectModel.isEnabled();
            }).toList();

Upvotes: 2

Views: 77

Answers (2)

Dave Moten
Dave Moten

Reputation: 12087

The toList operator emits a mutable List as you've noted (java.util.ArrayList). Just map it to the immutable list type of your choice. For example:

obs.toList()
   .map(Collections::unmodifiableList);

or using guava:

obs.toList()
   .map(ImmutableList::copyOf);

Upvotes: 3

Sergio Vargas
Sergio Vargas

Reputation: 93

so the answer as to why i was experiencing my issues is explained here:

http://www.javacreed.com/modifying-an-unmodifiable-list/

adding

.map(Collections::unmodifiableList)`

fixed it

Upvotes: 1

Related Questions