Filter sublist using RxJava

2019-08-11 08:20发布

问题:

Using the following objects :

Order {
 int orderId;
 List<Item> items; 
}

Item {
 int price;
 String description;
 boolean free; 
}

The goal is to keep non-free items starting from an Observable<0rder> and still return an Observable<0rder>.

I'm doing the following for now, but my items doesn't get filtered :

    getMyOrder() // returns Observable<Order> from the network
    .subscribeOn(Schedulers.io())
    .observeOn(Schedulers.computation())
    .flatMap(
       order -> Observable.from(order.items)
                        .filter(item -> !item.isFree())
                        .map(items -> order)
       );

回答1:

This doesn't feel like something that should be done using RxJava (especially if you want to emit Order after the filtering step), could be an instance method in Order, for example:

getMyOrder().subscribeOn(Schedulers.io())
        .observeOn(Schedulers.computation())
        .map(Order::removeFreeItems)
        .subscribe();

class Order {
    int orderId;
    List<Item> items;

    public Order removeFreeItems() {
        for (Iterator<Item> iterator = items.iterator(); iterator.hasNext(); ) {
            if (iterator.next().free) {
                iterator.remove();
            }
        }
        return this;
    }
}