英文:
Smart way to handle nested flux operations
问题
以下是代码段的翻译结果:
private Mono<List<Student>> find(String name) {
    return repo.findByName(name)
            .flatMap((List<Student> students) -> {
                return repo.findAnotherName(anothName, 1).collectList()
                        .flatMap((List<Student> anotherStudents) -> {
                            //进行一些逻辑操作
                            return Mono.just(students);
                        });
            });
}
英文:
I have 2 query methods (findByName/findAnotherName) .
Both of them return Mono<List<Student>> .
I do some logic by compare results of these two methods, and then return one of them in a nested Flux operation.
It may have a smart way to achieve same result though.
Following is code snippet:
private Mono<List<Student>> find(String name) {
	return repo.findByName(name)
			.flatMap((List<Student> students) -> {
				return repo.findAnotherName(anothName, 1).collectList()
						.flatMap((List<Student> anotherStudents) -> {
							//do some logic
							return Mono.just(students);
						});
			});
}
Thanks in advance.
答案1
得分: 0
以下是您要翻译的内容:
如果您的 //进行一些逻辑 是同步的,那么我可以提供类似这样的建议:
private Mono<List<Student>> find(String name) {
    return repo.findByName(name)
            .zipWhen((List<Student> students) -> {
                return repo.findAnotherName(anothName, 1).collectList();
            }, (students, anotherStudents) -> {
                //一些同步逻辑
                return students;
            });
}
但如果逻辑也是异步的,那么:
private Mono<List<Student>> find(String name) {
    return repo.findByName(name)
            .zipWhen((List<Student> students) -> {
                return repo.findAnotherName(anothName, 1).collectList()
                        .flatMap(anotherStudents -> someAsyncMethod(anotherStudents));
            }, ((students, o) -> students));
}
英文:
If your //do some logic is sync then I can suggest something like
private Mono<List<Student>> find(String name) {
    return repo.findByName(name)
            .zipWhen((List<Student> students) -> {
                return repo.findAnotherName(anothName, 1).collectList();
            }, (students, anotherStudents) -> {
                //some sync logic
                return students;
            });
}
But if the logic is also async, then
private Mono<List<Student>> find(String name) {
    return repo.findByName(name)
            .zipWhen((List<Student> students) -> {
                return repo.findAnotherName(anothName, 1).collectList()
                        .flatMap(anotherStudents -> someAsyncMethod(anotherStudents));
            }, ((students, o) -> students));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论