【发布时间】:2020-04-03 06:33:15
【问题描述】:
内置Merge 运算符的行为是在两个源都完成时完成。我正在寻找这个运算符的变体,它产生一个可观察的,当两个源可观察的 any 完成时完成。例如,如果第一个 observable 成功完成,稍后第二个 observable 完成但出现异常,我希望忽略此异常。
我想出了一个实现,它将一个特殊的哨兵异常连接到两个枚举,然后合并的序列捕获并抑制这个异常。我想知道我是否缺少更简单的解决方案。
/// <summary>
/// Merges elements from two observable sequences into a single observable sequence,
/// that completes as soon as any of the source observable sequences completes.
/// </summary>
public static IObservable<T> MergeUntilAnyCompletes<T>(this IObservable<T> first,
IObservable<T> second)
{
var sentinel = new Exception();
first = first.Concat(Observable.Throw<T>(sentinel));
second = second.Concat(Observable.Throw<T>(sentinel));
// Concat: Concatenates the second observable sequence to the first
// observable sequence upon successful termination of the first.
return first.Merge(second)
.Catch(handler: (Exception ex) =>
ex == sentinel ? Observable.Empty<T>() : Observable.Throw<T>(ex));
// Catch: Continues an observable sequence that is terminated by an exception
// of the specified type with the observable sequence produced by the handler.
}
【问题讨论】:
标签: c# system.reactive rx.net