我在Rest Web服务中使用RxJava2 Observable.fromIterable()。 我的示例iterable由三个元素组成,但是我的非阻塞休息服务仅返回三个元素中的一个。
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()));
}
}
当我从我的Non-Blocking 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"
}
如果我将我的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"
}
答案 0 :(得分:1)
如果将doOnNext
放在订阅之前,您会看到您有多个元素,但是显然JsonResponse只能传递一个。我敢打赌,您的非反应式版本只是将整个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))
);
};