最后在 rxjs 上序列在第一个错误时执行

Finally on rxjs sequence gets executed on first error

我尝试在 Observable 上执行 finally 语句 - http 调用序列。

finally 方法在第一个错误时执行,而不是在整个序列完成时执行。

deleteLeistungsTarife(
    leistungsTarife: Shopeinstellungen.LeistungsTarif[],
    leistungstarifGeloeschtCallback: (leistungsTarif: Shopeinstellungen.LeistungsTarif) => any) {
    let observerListe: Observable<number>[] = [];
    leistungsTarife.forEach((lt) => observerListe.push(
        this.http.delete(this._leistungenUrl + '/DeleteLeistungsTarif/' + lt.tarifLeistungId)
            .map(res => leistungstarifGeloeschtCallback(lt))
            .catch(this.handleError)                
    ));
    return Observable.forkJoin(observerListe).finally(()=>console.log("finally"));
}

此方法的调用如下所示:

    this._leistungenService.deleteLeistungsTarife(
        zuLoeschendeTarife, leistungsTarif => {
            console.log("gespeichert: ", leistungsTarif)
        }
    ).subscribe(
        (r) => console.log("liste result:", r),
        (e) => console.log("liste error:", e),
        () => console.log("complete")
    )

即使没有错误,最终和完整的控制台日志也会在第一个 observable 完成后被命中:/

是否有替代函数?

这是 finally 函数的预期和记录行为。检查 documentation

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

同样根据 Rxjs 语法,一个 observable 只能发出一个错误,这意味着 completion when an error occurs:

Messages sent to instances of the Observer object follow the following grammar: onNext* (onCompleted | onError)?

This grammar allows observable sequences to send any amount (0 or more) of onNext messages to the subscribed observer instance, optionally followed by a single success (onCompleted) or failure (onError) message.

The single message indicating that an observable sequence has finished ensures that consumers of the observable sequence can deterministically establish that it is safe to perform cleanup operations.

A single failure further ensures that abort semantics can be maintained for operators that work on multiple observable sequences.

要仅在可观察对象完成时调用函数,您可以使用两种主要技术:

  • doOnCompleted
  • 使用 materializeonNextonErroronCompleted 视为常规值(并使用 dematerialize 恢复正常行为)。

然而,在您的特定情况下,我认为方法是:

  • catch 错误,并用错误代码替换错误(即不要抛出或强制终止流,return 封装错误的值)。这样源代码和 forkJoin 也能正常完成。

我没有看到您的处理程序的代码,但我想它可能终止了它的可观察对象?如果是这种情况,您可以 return 一个错误代码,并在所有调用完成后使用 forkJoin.

resultSelector 参数分析所有调用的值