gpt4 book ai didi

java - Observable from iterable 不会打印所有元素

转载 作者:行者123 更新时间:2023-12-02 10:39:17 26 4
gpt4 key购买 nike

我在 Rest Web 服务中使用 RxJava2 Observable.fromIterable() 。我的示例迭代由三个元素组成,但我的非阻塞休息服务仅返回三个元素中的一个。

class ToDoDaoImpl implements ToDoDao {
Map<String, ToDo> toDos;
...
public Observable<ToDo> readAll() {
return Observable.fromIterable(toDos.entrySet().stream().map(entry -> entry.getValue()).collect(Collectors.toList()));
}
}

当我从非阻塞 Rest 库调用 readAll() 方法时,我只在三个元素上获取一个元素:

@Api(path = "/api/v2/read", method = "GET", produces = "application/json")
Action readAllToDos = (HttpServletRequest request, HttpServletResponse response) -> {
Observable.just(request)
.flatMap(req -> toDoDao.readAll())
.subscribe(output -> toJsonResponse(request, response, new ResponseDto(200, output)),
error -> toJsonResponse(request, response, new ResponseDto(200, error))
);
};

我的输出:

{
"status": 200,
"response": {
"id": "5dc74dd8-1ea9-427e-8bb7-482cc6e24c71",
"title": "learn ReactiveJ",
"description": "learn to use ReactiveJ library",
"date": {
"year": 2018,
"month": 10,
"day": 29
}
},
"datetime": "Oct 29, 2018 4:19:51 PM"
}

如果我将非响应式(Reactive)称为我的 Dao,我会得到我所期望的:

{
"status": 200,
"response": [
{
"id": "25cbe3bf-12be-42e4-82ce-d4780f6469f6",
"title": "study reactive",
"description": "learn reactive programming",
"date": {
"year": 2018,
"month": 10,
"day": 29
}
},
{
"id": "51879241-f005-43fa-80fb-78386b663cb7",
"title": "learn ReactiveJ",
"description": "learn to use ReactiveJ library",
"date": {
"year": 2018,
"month": 10,
"day": 29
}
},
{
"id": "80a07c1b-2317-4eb8-9a39-ac35260f37a2",
"title": "exercise",
"description": "do some exercises",
"date": {
"year": 2018,
"month": 10,
"day": 29
}
}
],
"datetime": "Oct 29, 2018 4:37:05 PM"
}

最佳答案

如果您在订阅之前放置 doOnNext ,您将看到获得多个元素,但显然 toJsonResponse 只能传递一个元素。我敢打赌,您的非响应式版本只是将整个 List 传递给 ResponseDto

我不确定为什么你使任务复杂化,但这应该可行:

class ToDoDaoImpl implements ToDoDao {
Map<String, ToDo> toDos;
// ...
public Observable<List<ToDo>> readAll() {
return Observable.fromCallable(() -> new ArrayList<>(toDos.values()));
}
}

@Api(path = "/api/v2/read", method = "GET", produces = "application/json")
Action readAllToDos = (HttpServletRequest request, HttpServletResponse response) ->
{
toDoDao.readAll()
.subscribe((List<ToDo output) ->
toJsonResponse(request, response, new ResponseDto(200, output)),
error ->
toJsonResponse(request, response, new ResponseDto(200, error))
);
};

关于java - Observable from iterable 不会打印所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53048979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com