Aks4125
Aks4125

Reputation: 5720

RxJava: remove element from list

I have tried various operators for iterating objects using map, concatMap,all but i am not able to remove element from my list.

Here is a piece of code:

  Observable.fromIterable(selectedJobs)
            .observeOn(AndroidSchedulers.mainThread()) // Added this from one answer in SO. but still no resolution.
            .all(homeJob -> {

                if (!homeJob.isCanCloseJob()) {
                    selectedJobs.remove(homeJob); // <- this is what causing Exception
                    //toast message
                } else {
                    //do something
                }

                return true;
            })
            .subscribe(new SingleObserver<Boolean>() {
                @Override
                public void onSubscribe(Disposable disposable) {

                }

                @Override
                public void onSuccess(Boolean aBoolean) {

                    baseRealm.executeTransaction(realm -> realm.copyToRealmOrUpdate(selectedJobs));

                }

                @Override
                public void onError(Throwable throwable) {
                    AppLogger.e(tag, throwable.getMessage());
                 // throws Caused by: java.util.ConcurrentModificationException
                }
            });

All I want is to check for condition then remove object from list.

Upvotes: 3

Views: 3212

Answers (1)

azizbekian
azizbekian

Reputation: 62189

In functional programming you are working with streams. Instead of removing an item from the initial input you have to filter the stream itself and pass the filtered list to the consumer.

Seems like this is what you are looking for:

Observable.fromIterable(listOfElements)
          .filter(element -> {
              if (element.isValid()) {
                  // do some action with valid `element`
                  // NOTE: this action would be performed with each valid element
                  return true;
              } else {
                  // `element` is not valid, perform appropriate action
                  // NOTE: this action would be performed for each invalid element
                  return false;
              }
          })
          .toList() // collect all the filtered elements into a List
          .subscribe(
                  filteredElements -> /* use `filteredElements` which is List<Element> */, 
                  throwable -> /* perform appropriate action with this `throwable`*/)
          );

Upvotes: 3

Related Questions