RxJS 管道 Finalize 运算符未被调用

RxJS pipe Finalize operator not getting called

import {
    Observable,
    BehaviorSubject
} from 'rxjs';
import {
    finalize,
    share
} from 'rxjs/operators'

export class someComponent() {

    public count$ = new BehaviorSubject < any > (0);

    public constructor() {
        this.shareResponse()
            .pipe(
                finalize(() => {
                    console.log('finalize called');
                }))
            .subscribe((event: any) => {
                // Do something
            });
    }
    public shareResponse(): Observable < any > {
        return this.count$.pipe(share());
    }
    public countChanged(event) {
        this.count$.next(event);
    }
}

HTML:

    <some-tag(countChanged) = (countChanged($event)) > < /some-tag>

BehaviorSubject 不会完成,除非您通过调用自己完成它 this.count$.complete()。这就是 finalize() 没有发生的原因,因为它正在等待 Observable 完成。

查看 StackBlitz 上的代码示例,参见 link

不确定你想用上面的代码做什么,但你可以在 pipe() 中的 finalize() 运算符之前使用 take(1) 来强制它在第一个发射值。