WillOw
WillOw

Reputation: 185

Why would pipe-> finalize not be called for an observable when the observable completes, but a callback in subscribe would be called?

I am working on code that needs to take some action when an observable completes. I was originally using pipe(finalize(() => {})), but I was finding that when the observable completes, the finalize callback was not being called. When I switched from a pipe to a subscription, then completion callback is called.

In the code below, "completed?" prints, but "Finalize called" does not

this.sweepRunner.start(parameters).then(output => {
        this.output = output;
        output.subscribe(null, null, () => {
            console.log("This will be called");
        });
        output.pipe(finalize(() => {
            console.log("This won't be called")}))
    });

Upvotes: 0

Views: 951

Answers (1)

Picci
Picci

Reputation: 17762

The key point is that you subscribe to output and not to output.pipe(...).

In other words, output.pipe(finalize(....)) creates a new Observable starting from the output Observable. So the code should look like this

this.sweepRunner.start(parameters).then(output => {
        const newObservable = output.pipe(finalize(() => {
            console.log("Finalize called");
            this.stateController.requestAction(
                this.stateController.patchActionFor<IDetectionLaserMotorState>(StateProperties.detectionMotorState)({
                    LRPosition: this.optimalState.position}))}))


        newObservable.subscribe(null, null, () => {
            console.log("completed?");
        });
    });

Upvotes: 2

Related Questions