(https://i.stack.imgur.com/2zm2w.png)
collectionData(queryRef).subscribe((data) => {
for (const each of data) {
this.getCourse(each.courseId)
.pipe(take(1))
.subscribe((courseData) => {
const course = courseData[0];
console.log(course);
this.getLecturer(course.lecturerId).pipe(take(1)).subscribe((res: any)=>{
const lecturer = res[0];
course.lecturerName = lecturer.lecturerName;
course.lecturerImageUrl = lecturer.lecturerImageUrl;
});
recentVisit.push(course);
});
}
});
Hi I am still new to the rxjs of Angular.
I am building an Ionic app using Angular Fire.
I’m currently facing some problems here, I’m using Firebase as my backend, and I would have to query through different collections to fetch my data. For example, the first subscription only fetch user course enroll data like courseId, progress…, the second subscription would fetch the course details, and the third will fetch lecturer details. Can anyone give some suggestion on how to avoid using nested subscription because many people said it is not recommended to do so.
I would be very appreciated if you can provide some detailed explainations because I really only know the basics of rxjs.
I have tried concatMap but it shows firebase error(https://i.stack.imgur.com/6SOS0.png)]
collectionData(queryRef)
.pipe(
concatMap((res: any) => this.getCourse(res.courseId))
//concatMap((result2: any) => this.getLecturer(result2.lecturerId))
)
.subscribe((res) => {
console.log(res);
});
But actually I also not sure did I did it right because I really cannot understand how concatMap works.
2
Answers
If you use nested Subscriptions, it means it would wait for the first the return a value, then call the second one and so one. Which costs alot of time.
What you could use on this is forkJoin():
forkJoins waits for all 3 Observables to emit once and gives you all the values.
Example here: https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin
I created a solution that prevents nested pipes as well as multiple explicit subscriptions by doing the following:
switchMap
andforkJoin
getMergedCourseDetails()
in order to keep the main pipe flat