0

I get an Unsupported Operation Exception when trying to modify a list from inside "apply" method of flatmap in RxJava2.

compositeDisposable.add(createObservable()
            .flatMap(new Function<List<String>, ObservableSource<List<String>>>() {
                @Override
                public ObservableSource<List<String>> apply(List<String> s) throws Exception {

                    List<String> modiList = new ArrayList<String>();
                    modiList.addAll(s);
                    modiList.add("barber");

                    //s.add("barber") and return Observable.fromArray(s) thows error

                    return Observable.fromArray(modiList);
                }
            })
            .subscribeWith(getObserver()));

However, If i create a new list it works fine as shown above. Any insights about it ?

Below is my Observable creation logic :

String[] arr = {"hi", "hello", "bye"};
Observable<List<String>> observable;
observable = Observable.fromCallable(() -> Arrays.asList(arr));
Gaurav
  • 667
  • 2
  • 13
  • 28
  • The problem probably lies in your `createObservable` i.e. you're emitting objects that don't support `addAll`. – JohnWowUs Jan 16 '17 at 09:05
  • Mutating values is not recommended as different stages may access the same data concurrently. But if this happens, you get a `ConcurrentModificationException`. `UnsupportedOperationException` happens when you try to call a method that is not supported, such as `remove()`. What is the exact stack trace? – akarnokd Jan 16 '17 at 09:05
  • @JohnWowUs Here's how i am creating observable : String[] arr = {"hi", "hello", "bye"}; Observable> observable; observable = Observable.fromCallable(() -> Arrays.asList(arr)); – Gaurav Jan 16 '17 at 09:46

1 Answers1

1

As akarnokd as pointed out, mutating the value of the list in your flatMap is generally a bad idea, but your superficial problem is that implementation of the interface List returned by Arrays.asList does not implement addAll.

JohnWowUs
  • 3,053
  • 1
  • 13
  • 20