Photo of Gil Creque in a pink TV

Returning Observable objects from combineLatest()

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.

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

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 })));

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 obfuscation! Let me know if you have any other ideas regarding this!

Tags: web-devangularrxjs