问题
I have a SubjectReplay and I would like to reset it to no cache values so after this reset the next subscriber doesn't get the history?
Example
- new subject replay
- subject.next(1)
- reset subject <- this question
- subject.subscribe() // should NOT receive 1
how can I do this? I need the subject to be the same instance.
回答1:
You may look at using a combination of special values and filter
operator to get something close to what you are trying to achieve.
Let's make a simple case.
You want to replay just the last value and null
is the special value representing the reset. The code would be
const rs = new ReplaySubject<any>(1); // replay the last value
const rsObs = rs.asObservable().pipe(filter(d => d !== null));
rs.next(1);
rs.next(2);
setTimeout(() => {
console.log('first subscription');
rsObs.subscribe(console.log) // logs 2 on the console
}, 10);
setTimeout(() => {
rs.next(null);
}, 20);
setTimeout(() => {
console.log('second subscription');
rsObs.subscribe(console.log) // nothing is logged
}, 30);
回答2:
The best way that comes to my mind with your requirement
I need the subject to be the same instance
would be to have the following observables:
// This is your input
const source$: Observable<T>;
const proxy$ = new ReplaySubject<T>(n);
const reset$ = new BehaviorSubject<number>(0);
Now it's important that we hook up the following before you emit on source$
:
source$.pipe(timestamp()).subscribe(proxy$);
Then, finally, you can expose your data like this:
const data$ = proxy$.pipe(
withLatestFrom(reset$),
filter(([timedItem, resetTimestamp]) => timedItem.timestamp > resetTimestamp),
map(([timedItem]) => timedItem.value),
);
You can now use reset$.next(+new Date())
to trigger the reset.
If you can make sure to provide timestamped values to source$
, you can skip the proxy$
.
来源:https://stackoverflow.com/questions/50996348/how-to-clean-clear-cache-of-a-subjectreplay-instance-in-rxjs