From 3f16e316b0e93e22c52840cc2eea9e9e3ffd9c57 Mon Sep 17 00:00:00 2001 From: erri120 Date: Sat, 10 Aug 2024 19:16:33 +0200 Subject: [PATCH] Add `WhereNotNull` operator Using optimized `WhereSelect`, the `WhereNotNull` operator is very common and many libraries and applications had to DIY implement this for `System.IObservable`. --- src/R3/Operators/WhereNotNull.cs | 13 ++++++++++ .../OperatorTests/WhereNotNullTest.cs | 24 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/R3/Operators/WhereNotNull.cs create mode 100644 tests/R3.Tests/OperatorTests/WhereNotNullTest.cs diff --git a/src/R3/Operators/WhereNotNull.cs b/src/R3/Operators/WhereNotNull.cs new file mode 100644 index 00000000..70b632c1 --- /dev/null +++ b/src/R3/Operators/WhereNotNull.cs @@ -0,0 +1,13 @@ +namespace R3; + +public static partial class ObservableExtensions +{ + public static Observable WhereNotNull(this Observable source) where TResult : class + { + return new WhereSelect( + source: source, + selector: static item => item!, + predicate: item => item is not null + ); + } +} diff --git a/tests/R3.Tests/OperatorTests/WhereNotNullTest.cs b/tests/R3.Tests/OperatorTests/WhereNotNullTest.cs new file mode 100644 index 00000000..5f8057d0 --- /dev/null +++ b/tests/R3.Tests/OperatorTests/WhereNotNullTest.cs @@ -0,0 +1,24 @@ +namespace R3.Tests.OperatorTests; + +public class WhereNotNullTest(ITestOutputHelper output) +{ + [Fact] + public void WhereNotNull() + { + var p = new Subject(); + + using var list = p.WhereNotNull().ToLiveList(); + + p.OnNext(null); + list.AssertEqual([]); + + p.OnNext("foo"); + list.AssertEqual(["foo"]); + + p.OnNext(null); + list.AssertEqual(["foo"]); + + p.OnNext("bar"); + list.AssertEqual(["foo", "bar"]); + } +}