在RxJava2中使用flatMap或zip?

时间:2018-03-08 16:18:19

标签: rx-java rx-java2

我有一个名为Student的课程,它有两个字段gradeschool。需要从远程服务器获取两个字段。当两个结果返回时,我新建了一个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());

flatMap版本

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);
        });

zip版

 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似乎更清楚。那么在这种情况下,运营商flatMapzip更好

1 个答案:

答案 0 :(得分:4)

你显然正在构成两个可观察的,这是zip()的目的。不仅如此,gradeObservableschoolObservable将与zip()并行执行,而您的flatmap()解决方案会序列化请求。所以,是的,zip()更好。