在谈到 Observables(尤其是 rxjs)时,“finally”和“done”或“complete”有什么区别?
最佳答案
finally 总是在可观察序列终止时发生(包括错误);完成仅在它无错误终止时发生。
最后:
Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/finally.md
已完成:
An Observable calls this method after it has called
onNext
for the final time, if it has not encountered any errors.
http://reactivex.io/documentation/observable.html
“完成”不是 rx/observables 的概念。我刚刚看到它打印在“Complete”/“OnComplete”的示例中。
注意:当您调用
subscribe
时,语法通常是:observable.subscribe([observer] | [onNext], [onError], [onCompleted]);
// Like this:
observable.subscribe(
(value) => { ... },
(error) => { ... },
() => { console.log('complete!'); }
);
或者
observable.subscribe({
next: x => console.log('got value ' + x),
error: err => console.error('something wrong occurred: ' + err),
complete: () => console.log('done'),
});
鉴于
finally
处理方式如下:observable.finally(() => { console.log('finally!'); })
.subscribe(...) // you can still call subscribe
关于rxjs - 可观察的 : Complete vs finally vs done,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44770999/