I'm trying to create a polling system that polls the backend on interval.
I have a method add
that takes a pollingItem that contains the command as a string and the refreshTime for the interval, and passes the observable created from the interval into a subject.
this.sideEffect
is the function passed into the class constructor on init that communicates with the backend.
There are two types of intervals that I want to create:
A default one that can be stopped when the subject linked to the command in the IntervalMap is called.
A 'SWITCH' one that can be stopped in the same manner as above, but also when a new pollingItem is added.
add(pollingItem, type = 'DEFAULT') {
this.intervalMap = { ...this.intervalMap, [pollingItem.command]: new Subject() };
switch (type) {
case 'SWITCH': {
const poller = interval(pollingItem.refreshTime).pipe(
takeUntil(this.intervalMap[pollingItem.command]),
takeUntil(this.onAdd$),
tap(() => {
this.sideEffect(pollingItem.command);
})
);
this.poll$.next(poller);
break;
}
default: {
const poller = interval(pollingItem.refreshTime).pipe(
takeUntil(this.intervalMap[pollingItem.command]),
tap(() => {
this.sideEffect(pollingItem.command);
})
);
this.poll$.next(poller);
break;
}
}}
My issue is that I want to have a way to combine the observables passed into poll$
over time.
Currently I have tried achieving this goal this way:
initialize() {
this.poll$
.pipe(
takeUntil(this.clear$),
scan((agg, current) => {
return [...agg, current];
}, [])
)
.subscribe(
poll => {
combineLatest(poll)
.pipe(takeUntil(this.onComplete$))
.subscribe(() => {
this.onAdd$.next();
});
},
() => {},
() => {
this.onComplete$.next();
}
);}
However while this does achieve the goal of combining the observables over time, it is limited because it restarts all the intervals on add, which is not the intended behavior.
I'm not sure where to go from here.
Any suggestions? I am still new to RxJS so any advice would be much appreciated, regardless if it's relevant to the topic.
Thank you!