It excites me to see rxjs observables in action and it confuses every single time, but each time I fell more in love with them.
Well, I have three observables -
- an observable that refreshed based on timer
this.autoRefreshView$
- a default observable that fetches based on today date
this.intraDayView
- an observable that fetches based on yesterday's date (let's say)
this.priorDayView$
There is a BehaviourSubject<>
that emits if default observable view is to be fetched (based on current date) or yesterday's view based on a view property - today
or yesterday
.
I want to execute this.autoRefreshView$
only when emitted value is today
. But, below it's executed if value is yesterday
as well. Is my merge here incorrect? Following is what I tried -
this.dashboardViewService.dashboardView$
.pipe(
mergeMap((v) =>
iif(
() => v === 'today',
merge(this.intraDayView$, this.autoRefreshView$),
this.priorDayView$
)
)
)
.subscribe((response) => {
if (response.date) {
this.dateService.setDate(response.date);
this.date= response.date;
}
});
This seems to work for me but the problem is when the view is not today
, it still gets into merge(this.intraDayView$, this.autoRefreshView$)
and executes this.autoRefreshView$
and updates the view, which I need to update only when event is today
and not yesterday
.
Any suggestion as what is missing? Please let me know if any other details are required.
I think it's because autoRefreshView
is emitted based on timer, so may be when it's called for first time, timer is set? Is there a way to handle that elegantly ?
this.autoRefreshView$ = timer(0, 25000).pipe(
switchMap(() => {
);
....
....
UPDATE - Updating the question with complete code snippet -
ngOnInit(): void {
this.intraDayView$ = this.api.getLatestData();
this.priorDayView$ = this.api.getPastData();
this.autoRefreshView$ = timer(0, 500000)
.pipe(
switchMap(() => {
// new data should be available, call the api
return this.api.getLatestData();
});
this.getDashboardView();
}
ngOnDestroy(): void {
this.dashboardViewSusbscription.unsubscribe();
}
getDashboardView() {
this.dashboardViewService.dashboardView$
.pipe(
switchMap((v) =>
iif(
() => v === 'today',
merge(this.intraDayView$, this.autoRefreshView$),
this.priorDayView$
)
)
)
.subscribe((response) => {
if (response.date) {
this.dateService.setDate(response.date);
this.date= response.date;
}
});
}