I have an observable that makes dynamic requests.
For example,
getFlowers(params?: any): Obeservable<Flower[]> {
return this.http.get<Flower[]>(
`http://flowers.com/flowers`, { params }
)
}
Now, the above function returns new http
observable each function call. I would like to somehow achieve returning the same observable instance (despite making different http calls) such that I can use switchMap
to cancel previous simultaneous requests.
I have an idea that I should create an Observable property (singleton), but I fail to realize how to utilize it.
Now, the above function returns new http observable each function call??
This is actually the normal behavior of the HTTP
observables as they are Cold.
When a cold observable
has multiple subscribers
, the whole data stream is re-emitted for each subscriber
. Each subscriber becomes independent and gets its own stream of data
Approach:1
To Avoid Duplication of HTTP Requests you can use shareReplay
operator.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs';
import {shareReplay,tap}from 'rxjs/operators';
@Injectable()
export class ShareService {
public response$:Observable<any>;
constructor(private httpc:HttpClient)
{
this.sendRequest();
}
public sendRequest()
{
this.response$= this.httpc.get('url').
pipe(tap(res=>{console.log('called');return res;}),shareReplay(1))
}
fetchData()
{
return this.response$;
}
}
component1:
constructor(service:ShareService)
{
service.fetchData().subscribe(result=>{
console.log(result);
})
component2:
constructor(service:ShareService)
{
service.fetchData().subscribe(result=>{
console.log(result);
})
Further Reading
Live Demo
Approach:2
If your objective is to multicast the data use RXJS's Subject
or BehaviorSubject
Subject
acts as a bridge/proxy between the source Observable
and many observers
, making it possible for multiple observers
to share the same Observable
execution.
This recommended way of exposing Subjects are using the asObservable()
operator.
@Injectable()
export class MyProvider {
private myObservable=new Subject<any>();
CurrentData = this.myObservable.asObservable();
constructor(private aFs: AngularFirestore) {
//your logic
this.myObservable.next(value);//push data into observable
}
}
Page.ts
this.mySubscription = this.myProvider.CurrentData.subscribe(value => {
//something that works
});
Using Behavior Subject
@Injectable()
export class MyProvider {
private myObservable=new BehaviorSubject<any>('');
CurrentData = this.myObservable.asObservable();
constructor(private aFs: AngularFirestore) {
}
getData(myParam): void {
someasynccall.pipe(map(),filter()).
subscribe(value=>this.myObservable.next(value))
}
Page.ts
this.myProvider.getData(param);
this.mySubscription = this.myProvider.CurrentData.subscribe(value => {
//something that works
});
Subject vs BehaviorSubject
LiveDemo