如何运行查询并返回计数

时间:2016-11-15 22:00:32

标签: java rx-java reactive-programming

下面的方法当前使用特定参数和限制查询数据库,当该查询完成时,它再次使用这些特定参数查询数据库,仅用COUNT(*)替换select部分以返回可能的总数查询的结果。

例如:

SELECT c1, c2 FROM table WHERE c1 = 'something'
SELECT count(*) FROM table WHERE c1 = 'something'

我想要做的是同时运行这两个查询,然后将结果合并到一个对象中,如下所示:

class SomethingResult {
  public List<T> data;
  public Long count;
}

如何用RxJava解决这个问题?

此外,RxJava是否适合此解决方案?

1 个答案:

答案 0 :(得分:0)

RxJava非常适合这种情况。在您的数据库类中:

//We'll use Single. Unlike Observable it returns only one value and then completes.
public Single<SomethingResult> getSomethingResultFromDb(Object params) {
    //we will use zip() operator to combine query results
    return Single.zip(
            doFirstQuery(params),
            doSecondQuery(params),
            (firstQueryResult, secondQueryResult) -> {
                //combine results into new SomethingResult
                return Single.just(somethingResult);
            });
}

private Single<List> doFirstQuery(Object params) {
    return Single.fromCallable(() -> { //or Single.defer()
        //your first db query with params
        return firstQueryResult;
    });
}

private Single<Long> doSecondQuery(Object params) {
    return Single.fromCallable(() -> { //or Single.defer()
        //your second db query with params
        return secondQueryResult;
    });
}

并像这样称呼它

 YourDbObject.getSomethingResultFromDb(params)
     //apply schedulers with subscribeOn() and observeOn() operators
     .subscribe(somethingResult -> {
         //handle result
     }, error -> {
         //handle error
     });