问题
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