How to do pattern matching in Rx. Where and Choose in one operator?

Suppose I have this type:

type T = int option 

and observable for this type:

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

I am looking for a better way to express this:

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

An observable that only applies to Some .

There are a few things that I don't like.

  • I use 2 operators
  • I match patterns twice
  • The second pattern match is not exhaustive (makes the visual studio display a warning and seems weird)
  • Too much code. The pattern is repeated every time I need pattern matching.
+6
source share
2 answers

Can't you use Observable.choose ? something like that:

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

If you have a type that is not an option, say:

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

and partial active template:

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

then you can do:

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

Thanks @Lee, I came up with a good solution.

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

This works for any type of union, not just the Option parameter.

+4
source

Source: https://habr.com/ru/post/988031/


All Articles