Use flatMap or zip in RxJava2?

五迷三道 提交于 2021-02-07 08:39:46

问题


I have a class called Student and it has two fields grade and school. Both of two fields need to be fetched from remote server. When two result returned, I new a Student object.

With help of RxJava, I have done it in two ways, one in flatMap and another in zip operator.

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 version

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 version

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

In my opinion, zip seems more clearly. So in this situation, operator flatMap or zip is better?


回答1:


You are clearly composing two observable, which is the purpose of zip(). Not only that but gradeObservable and schoolObservable would be executed in parallel with zip() whereas your flatmap() solution would serialize requests. So, yes, zip() is better.



来源:https://stackoverflow.com/questions/49177746/use-flatmap-or-zip-in-rxjava2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!