【问题标题】:Always return HttpStatus 200 (OK)总是返回 HttpStatus 200 (OK)
【发布时间】:2022-10-04 23:10:16
【问题描述】:

我们从 SQL Server 数据库中获取数据列表。我想在有数据时返回列表,但在没有数据时,我想返回“无内容”状态。我的代码:

public class Main {
  public static void main(String[] args) {
    var main = new Main();
    var result = main.controllerMethod();
    System.out.println("Result: " + result.blockingGet());
  }

  public Flowable<Person> personList(){
    List<Person> repositoryList = List.of();

    return repositoryList
        .stream()
        .collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
          if(list.isEmpty()) return Flowable.empty();
          else return Flowable.fromIterable(list);
        }));
  }

  public Maybe<ResponseEntity<Flowable<Person>>> controllerMethod(){
    var httpStatus =
        new AtomicReference<>(HttpStatus.OK);

    return Maybe.just(personList()
        .switchIfEmpty(subs -> Completable.fromAction(() ->
                httpStatus.set(HttpStatus.NO_CONTENT)).toFlowable()))
        .map(person -> ResponseEntity.status(httpStatus.get())
            .body(person));
  }
}

结果:

结果:<200 OK OK,io.reactivex.rxjava3.internal.operators.flowable.FlowableSwitchIfEmpty@35f983a6,[]>

【问题讨论】:

    标签: java java-stream rx-java reactive-programming


    【解决方案1】:

    您似乎希望 httpStatus.set(HttpStatus.NO_CONTENT) 运行,并且运行后,可以使用正确的状态码读取状态。我对响应式不是很熟悉,但是通过查看 Completable.java,我认为您在 Completable::fromAction 中提供的 Action 不会立即运行。

    可能有一种更被动的方式来解决问题,但我无法帮助你。相反,这是一个可能有效的解决方案(或至少让您朝着正确的方向前进)。只需在返回 Flowable 之前自己明确设置状态的值:

    public Flowable<Person> personList(AtomicReference<HttpStatus> reference) {
        List<Person> repositoryList = List.of();
    
        return repositoryList
                .stream()
                .collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
                    if (list.isEmpty()) {
                        reference.set(HttpStatus.NOT_FOUND);
                        return Flowable.empty();
                    }
                    return Flowable.fromIterable(list);
                }));
    }
    
    public Maybe<ResponseEntity<Flowable<Person>>> controllerMethod() {
        var httpStatus = new AtomicReference<>(HttpStatus.OK);
    
        return Maybe.just(personList(httpStatus))
                .map(person -> ResponseEntity.status(httpStatus.get()))
                .body(person));
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-04
      • 2019-03-02
      • 2018-01-14
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      相关资源
      最近更新 更多