RxJS5 finalize operator not called

二次信任 提交于 2019-12-05 22:37:21

问题


I'm trying to trigger a callback when all my observables are executed. In my other, older project i used finally like so and that worked like a charm:

this.myService.callDummy()
  .finally(() => console.log('Works!'))
  .subscribe(result => ...)

But now I'm using a newer version of RxJS with Pipeable operators, but the finally call (now renamed to finalize) never gets executed. There is little information to be found and I'm not sure what I'm doing wrong.

combineLatest(
  this.route.queryParams,
  this.myService.callDummy1(),
  this.myService.callDummy2()
)
.pipe(finalize(() => console.log('Does not work!')))
.subscribe(results => ...);

Any help is appreciated.


回答1:


In observables, firing and completing are not the same thing.

Even though each of the items emits a value, route.queryParams by definition will never complete since that is how Angular implements it, as a non terminating observable. You will need to manually complete it for your finalize to execute since combineLatest will only complete when EVERY observable being combined inside of it has completed.

combineLatest(
  this.route.queryParams.pipe(take(1)), // take(1) will complete the observable after it has emitted one value
  this.myService.callDummy1(),
  this.myService.callDummy2()
)
.pipe(finalize(() => console.log('Does not work!')))
.subscribe(results => ...);

this will complete.




回答2:


Are you sure one of combined Observables actually completes? With either .complete or .error?

If none of the combined Observables completes, finally will never be called.




回答3:


If you want to do something when the observable completes then use the complete callback instead of finally/finalize:

.subscribe(
    value => { console.log(`Next: ${value}`); },
    error => { console.log(`Error: ${error}`); },
    ()    => { console.log(`Completed`); }
);

Anyway finally/finalize should also work and will be called on error OR complete. Im pretty sure that your observable never completes. You can confirm this by using my code above.

I see you are using Angular and subscribing to this.route.queryParams which never completes. You may create a new observable by use of first() so you get the value and it immediatly completes: this.route.queryParams.pipe(first())



来源:https://stackoverflow.com/questions/49735826/rxjs5-finalize-operator-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!