DEV Community

Cover image for Returning Observable objects from combineLatest()
Gil
Gil

Posted on • Originally published at gilcreque.blog on

Returning Observable objects from combineLatest()

In trying to use more Reactive patterns in Angular I have been using the combineLatest() RxJs method to combine several Observables into one Observable and using the async pipe to use the data in the template. This ensures that all of the data is available in the template by using *ngIf. One thing I did not like about using combineLatest() is that it returns an array of results back based on the array of Observables you handed to it. This made accessing this data in the template look messy and made it harder to understand what data you were accessing.

cousePageData$: Observable<[User, Course]>;
const user$ = getCurrentUser(); // get the current user
const course$ = getCourse(courseId); // get course by course id
this.cousePageData$ = combineLatest([user$, course$]);
Enter fullscreen mode Exit fullscreen mode

In the template this would result in array([user, course]) as a result of using the async pipe (<div *ngIf="cousePageData$ | async as cousePageData>) and you would have to access user and course using the index on the array (cousePageData[0] and cousePageData[1]). As you can see, this obfuscates what data is actually being accessed at this indexes.

So I set out this morning to get this cleaned up in our repository and found a pretty easy solution in RxJs, using pipe and map to return the results of combineLatest() as an object.

cousePageData$: Observable<{user: User; course: Course;}>;
const user$ = getCurrentUser(); // get the current user
const course$ = getCourse(courseId); // get course by course id
const cousePageData$ = combineLatest([user$, course$])
                       .pipe(map(([user, course]) => ({ user, course })));
Enter fullscreen mode Exit fullscreen mode

In the template this would result in object({user: userData, course: courseData }) as a result of using the same async pipe and you can now access user and course using the property name on the object (cousePageData.user and cousePageData.course).

Yay for less obsfucation! Let me know if you have any other ideas regarding this!

Top comments (0)