Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use flatMap or zip in RxJava2?

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?

like image 858
CoXier Avatar asked Jul 25 '26 12:07

CoXier


1 Answers

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.

like image 198
Geoffrey Marizy Avatar answered Jul 27 '26 03:07

Geoffrey Marizy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!