user348173
user348173

Reputation: 9278

Delay between requests in flatMap

I have several requests that must be called one by one:

this.firstRequest()
.flatMap(resp => {
   //check response
   if(!response.success) {
      return Observable.throw('some message');
   }

   return this.secondRequest();
})
.subscribe(...)

firstRequest() {
 // build params and call http service
 return this.service.getData(...)
   .do(r => {
      if(r.success) {
         this.localStorage.save('code', r.code)
      }
    })
 .delay(5000); 
}

As you can see there is delay between first and second request. But, I need delay only when success field is true. How can I do it?

Upvotes: 3

Views: 1092

Answers (2)

Radu Cojocari
Radu Cojocari

Reputation: 1779

Here's some code that should help:

  ngAfterViewInit() {
      this.request1()
      .flatMap((response:any)=>{
        console.log(response);
        if(!response.success){
          return this.request2().delay(10000);
        }
        return this.request2();
      })
      .subscribe((response:any)=>{
        console.log(response.value);
      });
  }

  request1():Observable<any>{
    return Observable.create(observer=>{
      for(let i=0; i<2; i++){
        let success =i%2==0? true:false;
        observer.next({value:"request1:"+i,success:success});
      }
    });
  }

  request2():Observable<any>{
    return Observable.create(observer=>{
      for(let i=0; i<2; i++){
        observer.next({value:"request2:"+i});
      }
    });
  }
}

And the result of it: enter image description here

Upvotes: 4

CozyAzure
CozyAzure

Reputation: 8478

Method 1:

If you only want to do it solely in your firstRequest() method, then what you can do is return different observables via .of() inside a .flatMap():

firstRequest() {
    // build params and call http service
    return this.service.getData(...)
        .flatMap(r=>{
            if(r.success) { 
                this.localStorage.save('code', r.code);
                //delay for 500ms, then return the same response back
                return Observable
                    .delay(500)
                    .of(r);
            }
            //not successful, dont delay. return the original Observable
            return Observable.of(r);
        })
}

Method 2:

If you want to do it outside the method, then you can do this:

this.firstRequest()
    .flatMap(resp => {
        //check response
        if(!response.success) {
            return Observable.throw('some message');
        }
        return Observable
            .delay(500)
            .flatMap(()=>this.secondRequest())
    })
    .subscribe(...)

Either methods are okay, but you can't use both.

Upvotes: 3

Related Questions