RxJS 6 switchMap Deprecated Symbol used

Subhan picture Subhan · May 23, 2018 · Viewed 8.2k times · Source

I've updated from Angular 5 to Angular 6. Now I'm trying to update my code to make it compatible with RxJS 6.

.pipe(
  map(job => job[0]),
  switchMap((job) => {
    return job ? this.bookingService.findByID(job.property.id) : Observable.empty();
  }, (job: Job, bookings: Booking[]) => {
    this.mark_jobs_unavailable(job, bookings);
    return job;
  })
)

I'm getting warning on using switchMap that Deprecated Symbol is used.

These are my imports: import {map, switchMap} from 'rxjs/operators';

Is there any alternative way to use switchMap in v6? Also, If I don't change my code the rxjs-compat should make my existing code work (which i have installed) but I get the following error with the same code but in RxJS 5 style:

.map(job => job[0])
.switchMap((job) => {
    return job ? this.bookingService.findByID(job.property.id) : Observable.empty();
}, (job: Job, bookings: Booking[]) => {
    this.mark_jobs_unavailable(job, bookings);
    return job;
})

Error: Expected 1 argument but got 2.

Answer

siva636 picture siva636 · May 23, 2018

The resultSelector function given as the second argument to switchMap is deprecated. You need to remove this and achieve the goal using map operator.

The trickiest part here is to decide where to put the map operator. Actually the map operator to go inside the body of the function provided as the argument of switchMap.

The code without the result selector function will be something like the following:

     .pipe(
          map(job => job[0]),
          switchMap((job) => {
            return (job ? this.bookingService.findByID(job.property.id) : Observable.empty()).pipe(

              // This is the mapping function provided as the alternative to the deprecated result selector function
              // This should be placed inside the body of the function which is the 1st (and only one) argument of switchMap
              map((bookings: Booking[])=>{
              this.mark_jobs_unavailable(job, bookings);
              return job;
            })

            );
          }     
         )
        )