在RxJS 6中重置ReplaySubject [英] Resetting ReplaySubject in RxJS 6
问题描述
我有一个可过滤的活动日志",该日志当前使用 ReplaySubject
实现(因为一些组件在使用它,并且它们可能在不同的时间订阅).
I have a filterable 'activity log' that's currently implemented using a ReplaySubject
(since a few components use it and they might subscribe at different times).
当用户更改过滤器设置时,会发出一个新请求,但是结果会附加到 ReplaySubject
上,而不是替换它.
When the user changes the filter settings, a new request is made, however the results are appended to the ReplaySubject
rather than replacing it.
我想知道是否有任何更新 ReplaySubject
以仅使用 switchMap
之类的东西发送新项目的消息?
I was wondering if there is anyway to update the ReplaySubject
to only send through the new items using something like a switchMap
?
否则,我可能需要使用 BehaviorSubject
返回所有活动条目的数组,或者重新创建 ReplaySubject
并通知用户(可能通过使用另一个可观察的对象)取消订阅并重新订阅新的可观察对象.
Otherwise, I might need to either use a BehaviorSubject
that returns an array of all the activity entries or recreate the ReplaySubject
and notify users (probably by using another observable) to unsubscribe and resubscribe to the new observable.
推荐答案
如果您希望能够在不让其订阅者明确取消订阅和重新订阅的情况下重置主题,则可以执行以下操作:
If you want to be able to reset a subject without having its subscribers explicitly unsubscribe and resubscribe, you could do something like this:
import { Observable, Subject } from "rxjs";
import { startWith, switchMap } from "rxjs/operators";
function resettable<T>(factory: () => Subject<T>): {
observable: Observable<T>,
reset(): void,
subject: Subject<T>
} {
const resetter = new Subject<any>();
const source = new Subject<T>();
let destination = factory();
let subscription = source.subscribe(destination);
return {
observable: resetter.asObservable().pipe(
startWith(null),
switchMap(() => destination)
),
reset: () => {
subscription.unsubscribe();
destination = factory();
subscription = source.subscribe(destination);
resetter.next();
},
subject: source
};
}
resettable
将返回一个包含以下内容的对象:
resettable
will return an object containing:
- 可重设主题的订户应订阅的
observable
; - 您要在其上调用
next
,error
或complete
的主题
;和 -
重置
函数将重置(内部)主题.
- an
observable
to which subscribers to the re-settable subject should subscribe; - a
subject
upon which you'd callnext
,error
orcomplete
; and - a
reset
function that will reset the (inner) subject.
您将像这样使用它:
import { ReplaySubject } from "rxjs";
const { observable, reset, subject } = resettable(() => new ReplaySubject(3));
observable.subscribe(value => console.log(`a${value}`)); // a1, a2, a3, a4, a5, a6
subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);
observable.subscribe(value => console.log(`b${value}`)); // b2, b3, b4, b5, b6
reset();
observable.subscribe(value => console.log(`c${value}`)); // c5, c6
subject.next(5);
subject.next(6);
这篇关于在RxJS 6中重置ReplaySubject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!