Java – RxJava : remove element from list

RxJava : remove element from list… here is a solution to the problem.

RxJava : remove element from list

I’ve tried various operators to iterate over objects using map, concatMap, all, but I can’t remove elements from the 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
                }
            });

I just want to check the condition and then remove the object from the list.

Solution

In functional programming, you are using streams. Instead of removing items from the initial input, you have to filter the stream itself and pass the filtered list to the consumer.

It seems that 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`*/)
          );

Related Problems and Solutions