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());
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);
});
In my opinion, zip seems more clearly. So in this situation, operator flatMap or zip is better?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With