[英]Always return HttpStatus 200 (OK)
We obtain a list of data from a SQL Server database.我们从 SQL 服务器数据库中获取数据列表。 I want to return the list when there is data, but when there is not, I want to return a "No Content" status.
当有数据时我想返回列表,但是当没有数据时,我想返回一个“无内容”状态。 My code:
我的代码:
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));
}
}
result:结果:
Result: <200 OK OK,io.reactivex.rxjava3.internal.operators.flowable.FlowableSwitchIfEmpty@35f983a6,[]>
结果:<200 OK OK,io.reactivex.rxjava3.internal.operators.flowable.FlowableSwitchIfEmpty@35f983a6,[]>
It seems that you expect httpStatus.set(HttpStatus.NO_CONTENT) to be run, and after running, the status can be read with the correct statuscode.似乎您希望运行 httpStatus.set(HttpStatus.NO_CONTENT) ,运行后,可以使用正确的状态码读取状态。 I'm not very familiar with reactive, but by looking at Completable.java I don't think the Action that you provide in Completable::fromAction is run right away.
我对反应不是很熟悉,但是通过查看 Completable.java 我认为您在 Completable::fromAction 中提供的 Action 不会立即运行。
There is probably a more reactive-like way to solve the problem, but I can't help you there.可能有一种更像反应式的方法来解决这个问题,但我帮不了你。 Instead, here's a solution that might work (or at least get you going in the right direction).
相反,这里有一个可能有效的解决方案(或者至少让您朝着正确的方向前进)。 Just set the value of the status explicitly yourself before returning your Flowable:
在返回你的 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.