Ash
Ash

Reputation: 6035

Make Angular / RxJS more readable

I'm relatively new to RxJs and angular in general and wanted to know if there's a way to simplify the following code so it still does the same thing but is easier to read or is this as good as it can be?

private configureDS() {

let params$ = this.params$.pipe(debounceTime(300));
this.user$
  .pipe(
    mergeMap(user =>
      from(this.loadPosts(user)).pipe(map(posts => ({ user, posts })))
    ),
    combineLatest(this.dates$, params$),
    switchMap(([{ user, posts }, dates, params]) =>
      from(
        this.loadData(dates.date, dates.endDate, user, posts, params)
      ).pipe(map(data => ({ dates, data })))
    )
  )
  .subscribe(({ dates, data }) => this.displayData(data, dates));

this.paramsSubject.next(this.params);

}

Upvotes: 0

Views: 262

Answers (1)

Picci
Picci

Reputation: 17762

You can try something like this to improve readability a bit

let params$ = this.params$.pipe(debounceTime(300));
let userPosts$ = this.user$
  .pipe(
    mergeMap(user =>
      from(this.loadPosts(user)).pipe(map(posts => ({ user, posts })))
    ),
  );

combineLatest(userPosts$, this.dates$, params$)
.pipe(
    switchMap(([{ user, posts }, dates, params]) =>
      from(
        this.loadData(dates.date, dates.endDate, user, posts, params)
      ).pipe(map(data => ({ dates, data })))
    )
)
.subscribe(({ dates, data }) => this.displayData(data, dates));

This basically uses the combineLatest function instead of the combineLatest operator (which is depracted since RxJs 6).

Still there are some things not really clear to me. For instance, why to you use the from function with this.loadPosts(user)? Usually from takes an iterable as input and returns a stream which emits per each element of the iterable - is loadPosts returning an iterable?

I ask these questions because maybe readability can be improved reviewing a bit the design of the chain.

Upvotes: 1

Related Questions