Search code examples
rxjsangular2-servicesangular2-observables

Switchmap on same function


I am not a rxjs expert.

I have a method which actually does a save.

 this.saveProducts(this.boxes, 'BOXES')

But there are two other different type of items that needs to use the same method for saving , just the parameter is different.

 this.saveProducts(this.containers, 'CONTAINER')

In my component I have few other independent saving is happening and all these should happen one by one.

So my method look like this.

 return this.service.edit(materials)
        .do((data) => {
            this.materials= data;
        })
        .switchMap(() => this.customerService.addCustomer(this.id, this.customers))
        .switchMap(() => this.saveProducts(this.boxes, 'BOXES'))
        .switchMap(() => this.saveProducts(this.containers, 'CONTAINER'))
        .switchMap(() => this.saveProducts(this.books, 'BOOKS'))
        .do(() => {
         .......
            }

But whats happening is it never calls the second saveProducts method unless I have a return from first one

    private saveProducts(products: IProduct[], type: 
Type): Observable<any> {
        console.log(type);
    }

Solution

  • Thanks for anyone who looked at it.. The answer to this issue is to return an empty observable if nothing is there to save.

      if (products$.length === 0) {
            return Observable.of([]);
        }
    

    Thanks guys.. Happy coding..