谓词过滤器rxjava2 - 如何传递动态过滤器参数

时间:2017-11-15 08:41:59

标签: java reactive-programming rx-java2

我已经使用rxjava2构建了一些基本的过滤器,它按预期工作。我想知道如何将值/传递参数传递给过滤器(return td.getTypeId() == **<value>**;)。此外,如果某人有关于如何使用rxjava2 / filter构建(半)动态查询(Object.<field> == <value>)的想法/线索/示例,将会受到赞赏。

Predicate<TradeDetailed> testfilter;

Flowable<List<TradeDetailed>> td = tr.getTradesDetailedFlowable();

testfilter = new Predicate<TradeDetailed>() {
    @Override
    public boolean test(@NonNull TradeDetailed td) throws Exception {
        return td.getTypeId() == 0;
    }
};

Disposable d = td
        .flatMapIterable(e -> e)
        .filter(e-> testfilter.test(e))
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(t -> {
                        System.out.println("filtered "+t.getReference()));

                    },
                    err -> {
                        System.out.println("error");
                    }
        );

1 个答案:

答案 0 :(得分:1)

您可以为Predicate创建一个单独的类:

class YourPredicate implements Predicate<TradeDetailed>(){

    private final int compareAgainst;

    public YourPredicate(int compareAgainst){
        this.compareAgainst = compareAgainst;
    }

    @Override
    public boolean test(@NonNull TradeDetailed td) throws Exception {
        return td.getTypeId() == compareAgainst;
    }

}