Delay between requests in flatMap
I have several requests that need to be called one after the other:
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 a delay between the first and second requests. But I only need a delay when the field is success
true. How can i do this?
+3
source to share
2 answers
Method 1:
If you only want to do this in your method firstRequest()
, then what you can do is return different observables through .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 this outside of a method, 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(...)
Both methods are ok, but you cannot use both methods.
+3
source to share
Here's the 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});
}
});
}
}
+4
source to share