我有一个名为Student
的课程,它有两个字段grade
和school
。需要从远程服务器获取两个字段。当两个结果返回时,我新建了一个Student
对象。
在RxJava
的帮助下,我有两种方式,一种在flatMap
,另一种在zip
运营商。
Observable<String> gradeObservable =
Observable.create((ObservableOnSubscribe<String>) emitter -> {
Thread.sleep(1000);
emitter.onNext("senior");
}).subscribeOn(Schedulers.io());
Observable<String> schoolObservable =
Observable.create((ObservableOnSubscribe<String>) emitter -> {
emitter.onNext("MIT");
}).subscribeOn(Schedulers.io());
gradeObservable
.flatMap(grade ->
schoolObservable.map(school -> {
Student student = new Student();
student.grade = grade;
student.school = school;
return student;
}))
.subscribe(student -> {
System.out.println(student.grade);
System.out.println(student.school);
});
Observable.zip(gradeObservable, schoolObservable, (grade, school) -> {
Student student = new Student();
student.grade = grade;
student.school = school;
return student;
}).subscribe(student -> {
System.out.println(student.grade);
System.out.println(student.school);
});
在我看来,zip
似乎更清楚。那么在这种情况下,运营商flatMap
或zip
更好?
答案 0 :(得分:4)
你显然正在构成两个可观察的,这是zip()
的目的。不仅如此,gradeObservable
和schoolObservable
将与zip()
并行执行,而您的flatmap()
解决方案会序列化请求。所以,是的,zip()
更好。