Home > Back-end >  How to pass concatMap projection to subscribe next?
How to pass concatMap projection to subscribe next?

Time:02-25

How can I use the concatMap projection in the subscribe.next()?

    private onSomethingChange(): Subscription {
        // somethingChanged is a Subject
        return this.somethingChanged.pipe(
            concatMap(somethingProjection =>
                combineLatest([
                    this.firstObservable(somethingProjection),
                    this.secondObservable()
                ])
            )).subscribe(([firstResponse, secondResponse]) => {
                // I need to use somethingProjection here too
        });
    }

I found suggestions to use RxJS map, but I haven't found a way to use it correctly:

    private onSomethingChange(): Subscription {
        // somethingChanged is a Subject
        return this.somethingChanged.pipe(
           concatMap(somethingProjection =>
               combineLatest([
                   this.firstObservable(somethingProjection),
                   this.secondObservable()
               ]).pipe(map(([firstResponse, secondResponse]) => [somethingProjection, firstResponse, secondResponse])
           )).subscribe(([somethingProjection, firstResponse, secondResponse]) => {
               // ...
        });
   }

In the first code snippet, each item in the subscribe projection is of the correct type. If I replace the projection with just response, its type would be [firstResponseType, secondResponseType].
In the second code snippet, each item in the subscribe projection is of type somethingProjectionType | firstResponseType | secondResponseType. If I replace the projection with just response, its type would be (somethingProjectionType | firstResponseType | secondResponseType)[].
How to pass somethingProjection to the subcribe next so that each item in the array descrtion is of the correct type?

CodePudding user response:

Instead of returning an array from the map operator, you have to return an object with the required properties.

You can try something like the following:

private onSomethingChange(): Subscription {
  // somethingChanged is a Subject
  return this.somethingChanged
    .pipe(
      concatMap((somethingProjection) =>
        combineLatest([
          this.firstObservable(somethingProjection),
          this.secondObservable(),
        ]).pipe(
          map(([firstResponse, secondResponse]) => ({
            somethingProjection,
            firstResponse,
            secondResponse,
          }))
        )
      )
    )
    .subscribe(({ somethingProjection, firstResponse, secondResponse }) => {
      // ...
    });
}
  • Related