given the following code:
service:
getList(){
return return this.http.request("put", url_, options_)
}
component:
submitRequest(reset?){
this.httpService.getList().subscribe((response) => {
//if reset return an empty array
//server cannot return an empty array
})
}
and I want to do something like:
component:
submitRequest(reset?){
this.httpService.getList().pipe(someOperator(() => {
// if reset DO NOT MAKE HTTP CALL BUT INSTEAD RETURN []
})).subscribe((response) => {
//IF reset NO SERVER CALL WAS MADE BUT GOT [] FROM someOperator
//SERVER RESPONSE ONLY IF NO reset
})
}
how do i achieve this using RXJS ?
CodePudding user response:
something like: if (reset) return of([])?
submitRequest(reset?){
if (reset) return of([])
this.httpService.getList().pipe(someOperator(() => {
// if reset DO NOT MAKE HTTP CALL BUT INSTEAD RETURN []
})).subscribe((response) => {
//IF reset NO SERVER CALL WAS MADE BUT GOT [] FROM someOperator
//SERVER RESPONSE ONLY IF NO reset
})
}
CodePudding user response:
I would change the reset operator to an Observable<any> that does not emit anything immediately upon subscribing (e.g. not a BehaviorSubject), and then the code can change to:
private destroy$: Subject<void> = new Subject();
ngOnDestroy(): void {
this.destroy$?.next();
this.destroy$?.complete();
}
submitRequest(reset?: Observable<any>){
let o$ = this.httpService.getList();
if (reset) {
o$ = merge(o$, reset.pipe(mapTo([])));
}
o$.pipe(
first(),
takeUntil(destroy$)
).subscribe(response => whatever);
}
The subscriber function will
- not be called if your
thisgets destroyed. Otherwise, - received an empty array if
resetemits anything before the server response is received. Otherwise - receive the server response.
In any of these cases the subscription will be cancelled so it will clean itself up.
