我是rxjs
的新手,所以我可能不会像一个有经验的用户那样使用它。
我也在使用rxjs 5.1.0。
我有一个服务,其中有一个名为file$
的BehaviorSubject
和一个来自file$
的名为files
的observable
@Injectable()
export class UploadService {
files$: BehaviorSubject<FileToUpload[]> = new BehaviorSubject([]);
files: Observable<FileToUpload[]> = this.files$.asObservable();
将这些变量作为成员变量会让人感觉有点奇怪。
这是正确的吗,或者我可以做得更好吗?
然后在组件onInit
中订阅files
观察者:
ngOnInit() {
this.fileStateSubscription = this.uploadService.files.subscribe((files) => {
yt On ngDestroy
I正在取消订阅:
ngOnDestroy() {
this.fileStateSubscription.unsubscribe();
}
这样做对吗?我担心内存泄漏等问题,我应该以某种方式从files$
获得unsubscribing
。
我不能在ngOndestroy
中取消订阅files$
,或者至少我需要一些如何再次连接订阅,但由于它是一个成员变量,这会导致问题。
我应该在每次进入此组件时订阅和取消订阅吗?
发布于 2019-02-28 06:05:49
你应该取消订阅你订阅的每一个观察点,如果他们不能在时间内自己完成(热和冷观察点,你可能想要查一下,一个快速的谷歌搜索会给你多个博客)。在你自己托管主题的情况下,你绝对应该取消订阅。
有了这些成员变量,如果可以的话,您可能希望对可观察的文件使用getter。我不太确定这个约定,但我认为files变量的末尾也应该有一个$。
取消订阅的方式是正确的一个很好的方法,特别是当你在一个组件中有多个订阅时,就像这样使用takeUntil:
export class YouComponent implements OnInit, OnDestroy {
private unsubscribe$: Subject<void> = new Subject<void>();
constructor(private yourService: YouService) {}
ngOnInit(): void {
this.yourService.getFiles().pipe(takeUntil(this.unsubscribe)).subscribe(() => // some code)
this.yourService.getOtherFiles().pipe(takeUntil(this.unsubscribe)).subscribe(() => // some code)
}
ngOnDestroy(): void {
this.unsubscribe.next();
this.unsubscribe.complete();
}
}
这样,当this.unsubscribe发出时,您将取消对所有可观察对象的订阅。
啊,我刚读到你没有管道:我记得你可以用
yourService.getFiles().takeUntil(this.unsubscribe).subscribe()
相反,
https://stackoverflow.com/questions/54794111
复制相似问题