如何在 Rx 中进行模式匹配。 Where 和 Select 在单个运算符中?

How to do pattern matching in Rx. Where and Select in a single operator?

假设我有这种类型:

type T = int option

以及该类型的可观察对象:

let o : IObservable<T> = // create the observable

我正在寻找一种更好的表达方式:

o.Where(function | None -> false | Some t -> true)
 .Select(function | Some t -> t)

An observable that only propagates the Some case.

有几件事我不喜欢。

感谢@Lee,我想出了一个很好的解决方案。

o.SelectMany(function | None -> Observable.Empty() | Some t -> Observable.Return t)

这适用于任何联合类型,而不仅仅是 Option。

你不能用Observable.choose吗?像这样:

let o1 : IObservable<int option> = // ...
let o2 = Observable.choose id o1

如果您的类型不是一个选项,请说:

type TwoSubcases<'a,'b> = | Case1 of 'a | Case2 of 'b

和部分活动模式:

let (|SecondCase|_|) = function
    | Case1 _ -> None
    | Case2 b -> Some b

那么你可以这样做:

let o1 : IObservable<TwoSubcases<int, float>> = // ...
let o2 : IObservable<float> = Observable.choose (|SecondCase|_|) o1