su1212
su1212

Reputation: 87

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>

Upvotes: 2

Views: 3853

Answers (2)

AsGoodAsItGets
AsGoodAsItGets

Reputation: 3181

Not sure what you're trying to do with the code above, but you can use take(1) before the finalize() operator inside the pipe() to force it to finalize after the first emmitted value.

Upvotes: 1

Goga Koreli
Goga Koreli

Reputation: 2947

BehaviorSubject doesn't complete unless you complete it yourself by calling this.count$.complete(). That's why finalize() is not happening, since it is waiting for Observable completion.

Have a look at the code example on StackBlitz, see link.

Upvotes: 7

Related Questions