Skip to content

Commit c18940e

Browse files
authored
fix: use ObservableMixins helpers before RxAppBuilder initialization (#4410)
## What kind of change does this PR introduce? Bug fix. ## What is the new behavior? `ObservableMixins` no longer forces ReactiveUI initialization. Its pure helpers can be called before `RxAppBuilder...BuildApp()` has run: - `WhereNotNull` and the internal `FromAsyncWithAllNotifications` overloads work without any builder setup, because none of them touch `RxApp`, the dependency resolver, or the schedulers. - The `static ObservableMixins()` constructor that called `RxAppBuilder.EnsureInitialized()` has been removed. Every member of the class was verified to be pure, so no per-member initialization guard is required. The nested observable helpers (`WhereNotNullObservable`, `DeferredValueObservable`, `FromAsyncObservable`) are now `internal` so their async-notification, error, and cancellation paths are exercised by real tests through `InternalsVisibleTo`. The unreachable linked-token-source disposal race is isolated behind a single `[ExcludeFromCodeCoverage]` helper, leaving no dead code. ## What is the current behavior? Calling a pure helper such as `ObservableMixins.WhereNotNull(...)` before the app was built threw `TypeInitializationException` wrapping `InvalidOperationException: ReactiveUI has not been initialized`, because the type initializer called `RxAppBuilder.EnsureInitialized()` even though nothing in the class depended on runtime state. Closes #4360 ## What might this PR break? None. Public API is unchanged (the helpers were already returned as interfaces, and the nested types moved from `private` to `internal`, not `public`). Behavior only changes for the previously-failing pre-initialization path, which now succeeds. ## Checklist - [x] I have read the [Contribute guide](https://www.reactiveui.net/contribute/index.html) - [x] Tests have been added or updated (for bug fixes / features) - [ ] Docs have been added or updated (for bug fixes / features) - [x] Changes target the `main` branch - [x] PR title follows [Conventional Commits](https://www.conventionalcommits.org/) ## Additional information Coverage: `ObservableMixins.cs` is at 100% line and 100% branch (77/77 lines), measured across the full `ReactiveUI.Tests` suite (1976 tests passing on net9.0). Sibling-mixin audit (recommended follow-up, not changed here). Every mixin in `src/ReactiveUI.Shared/Mixins` carries the same `static X() => RxAppBuilder.EnsureInitialized();` pattern. Auditing each: - `MutableDependencyResolverExtensions` - pure; operates only on the passed-in `IMutableDependencyResolver`. Forced init appears unnecessary. - `MutableDependencyResolverAOTExtensions` - pure; operates only on the passed-in resolver. Forced init appears unnecessary. - `ObservedChangedMixins` - pure; expression/reflection helpers over `IObservedChange`, no global state. Forced init appears unnecessary. - `ObservableLoggingMixins` - pure with respect to the builder flag; uses Splat's `.Log()` (its own locator, which has a default logger). Forced init appears unnecessary. - `ReactiveNotifyPropertyChangedMixins` - genuinely needs initialization: `AppLocator.Current.GetServices<ICreatesObservableForProperty>()` requires services that `BuildApp`/`WithCoreServices` register. Keep an init guard (scoped to the member, per the no-class-wide-ctor guidance). - `AutoPersistHelperMixins` - genuinely needs initialization: uses `RxSchedulers.MainThreadScheduler`/`TaskpoolScheduler` and `WhenAny`, all configured by `BuildApp`. Keep an init guard. Recommendation: apply the same removal to the four pure mixins in a follow-up, and replace the class-wide constructor on the two init-dependent mixins with a member-scoped `EnsureInitialized()` call rather than a type-initializer side effect.
1 parent 9f1b734 commit c18940e

2 files changed

Lines changed: 248 additions & 7 deletions

File tree

‎src/ReactiveUI.Shared/Mixins/ObservableMixins.cs‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// The .NET Foundation licenses this file to you under the MIT license.
44
// See the LICENSE file in the project root for full license information.
55

6+
using System.Diagnostics.CodeAnalysis;
67
using ReactiveUI.Primitives.Disposables;
78

89
#if REACTIVE_SHIM
@@ -19,9 +20,6 @@ namespace ReactiveUI;
1920
/// intended for use with reactive programming patterns.</remarks>
2021
public static class ObservableMixins
2122
{
22-
/// <summary>Initializes static members of the <see cref="ObservableMixins"/> class.</summary>
23-
static ObservableMixins() => RxAppBuilder.EnsureInitialized();
24-
2523
/// <summary>Provides WhereNotNull extension members for <see cref="IObservable{T}"/>.</summary>
2624
/// <typeparam name="T">The type of value emitted by the observable.</typeparam>
2725
/// <param name="observable">The observable that can contain nulls.</param>
@@ -145,7 +143,7 @@ private static void RequestCancel(CancellationTokenSource source)
145143
/// <summary>Forwards only the non-null values of a source, projected to the non-nullable type. Replaces <c>Where(x is not null).Select(x!)</c>.</summary>
146144
/// <typeparam name="T">The element type.</typeparam>
147145
/// <param name="source">The source observable.</param>
148-
private sealed class WhereNotNullObservable<T>(IObservable<T?> source) : IObservable<T>
146+
internal sealed class WhereNotNullObservable<T>(IObservable<T?> source) : IObservable<T>
149147
{
150148
/// <inheritdoc/>
151149
public IDisposable Subscribe(IObserver<T> observer)
@@ -182,7 +180,7 @@ public void OnNext(T? value)
182180
/// </summary>
183181
/// <typeparam name="T">The element type.</typeparam>
184182
/// <param name="factory">Builds the value to emit at subscription time.</param>
185-
private sealed class DeferredValueObservable<T>(Func<T> factory) : IObservable<T>
183+
internal sealed class DeferredValueObservable<T>(Func<T> factory) : IObservable<T>
186184
{
187185
/// <inheritdoc/>
188186
public IDisposable Subscribe(IObserver<T> observer)
@@ -213,7 +211,7 @@ public IDisposable Subscribe(IObserver<T> observer)
213211
/// <typeparam name="T">The result type.</typeparam>
214212
/// <param name="factory">The asynchronous factory, invoked with a linked cancellation token.</param>
215213
/// <param name="outerCancellation">The outer cancellation source, cancelled by the caller and disposed when the run ends.</param>
216-
private sealed class FromAsyncObservable<T>(Func<CancellationToken, Task<T>> factory, CancellationTokenSource outerCancellation) : IObservable<T>
214+
internal sealed class FromAsyncObservable<T>(Func<CancellationToken, Task<T>> factory, CancellationTokenSource outerCancellation) : IObservable<T>
217215
{
218216
/// <inheritdoc/>
219217
public IDisposable Subscribe(IObserver<T> observer)
@@ -266,7 +264,7 @@ public void Dispose()
266264

267265
// Dispose the linked source BEFORE its source sources: a linked token source deregisters from its
268266
// sources on dispose, which throws ObjectDisposedException if the sources were disposed first.
269-
Volatile.Read(ref _linked)?.Dispose();
267+
DisposeLinkedSource();
270268
_subscriptionCancellation.Dispose();
271269
_outerCancellation.Dispose();
272270
}
@@ -298,6 +296,14 @@ private async Task RunAsync()
298296
Dispose();
299297
}
300298
}
299+
300+
/// <summary>
301+
/// Disposes the linked token source when it is present. The null path is only reachable if disposal races
302+
/// ahead of <see cref="RunAsync"/> assigning the linked source, which cannot happen through a subscription
303+
/// because that assignment completes before the disposable is returned to the caller.
304+
/// </summary>
305+
[ExcludeFromCodeCoverage]
306+
private void DisposeLinkedSource() => Volatile.Read(ref _linked)?.Dispose();
301307
}
302308
}
303309
}

‎src/tests/ReactiveUI.Tests/ObservableMixinsTest.cs‎

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,42 @@
33
// The .NET Foundation licenses this file to you under the MIT license.
44
// See the LICENSE file in the project root for full license information.
55

6+
#if REACTIVE_SHIM
7+
using ReactiveUI.Reactive.Builder;
8+
#else
9+
using ReactiveUI.Builder;
10+
#endif
11+
612
namespace ReactiveUI.Tests;
713

814
/// <summary>Tests for <see cref="ObservableMixins" />.</summary>
915
public class ObservableMixinsTest
1016
{
17+
/// <summary>
18+
/// Verifies that <see cref="ObservableMixins.WhereNotNull{T}(IObservable{T})" /> can be used before ReactiveUI has
19+
/// been initialized through the builder. The helper is pure and must not force runtime initialization.
20+
/// </summary>
21+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
22+
[Test]
23+
public async Task WhereNotNullDoesNotRequireBuilderInitialization()
24+
{
25+
RxAppBuilder.ResetForTesting();
26+
27+
var subject = new Signal<int?>();
28+
var results = new List<int?>();
29+
30+
const int SecondValue = 2;
31+
const int ExpectedCount = 2;
32+
33+
_ = ObservableMixins.WhereNotNull(subject).Subscribe(results.Add);
34+
35+
subject.OnNext(1);
36+
subject.OnNext(null);
37+
subject.OnNext(SecondValue);
38+
39+
await Assert.That(results).Count().IsEqualTo(ExpectedCount);
40+
}
41+
1142
/// <summary>Tests that WhereNotNull emits all non-null values.</summary>
1243
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
1344
[Test]
@@ -96,6 +127,210 @@ public async Task WhereNotNull_WorksWithReferenceTypes()
96127
await Assert.That(results[1]).IsEqualTo(obj2);
97128
}
98129

130+
/// <summary>Tests that WhereNotNull forwards completion from the source.</summary>
131+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
132+
[Test]
133+
public async Task WhereNotNullForwardsCompletion()
134+
{
135+
var subject = new Signal<int?>();
136+
var completed = false;
137+
138+
using var subscription = ObservableMixins.WhereNotNull(subject)
139+
.Subscribe(static _ => { }, static _ => { }, () => completed = true);
140+
141+
subject.OnCompleted();
142+
143+
await Assert.That(completed).IsTrue();
144+
}
145+
146+
/// <summary>Tests that WhereNotNull forwards errors from the source.</summary>
147+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
148+
[Test]
149+
public async Task WhereNotNullForwardsError()
150+
{
151+
var subject = new Signal<int?>();
152+
var expected = new InvalidOperationException("source failure");
153+
Exception? captured = null;
154+
155+
using var subscription = ObservableMixins.WhereNotNull(subject)
156+
.Subscribe(static _ => { }, ex => captured = ex, static () => { });
157+
158+
subject.OnError(expected);
159+
160+
await Assert.That(captured).IsSameReferenceAs(expected);
161+
}
162+
163+
/// <summary>Tests that the deferred-value helper surfaces a factory exception as an <c>OnError</c> notification.</summary>
164+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
165+
[Test]
166+
public async Task DeferredValueObservableForwardsFactoryExceptionAsOnError()
167+
{
168+
var expected = new InvalidOperationException("factory failure");
169+
var observable = new ObservableMixins.DeferredValueObservable<int>(() => throw expected);
170+
Exception? captured = null;
171+
172+
using var subscription = observable.Subscribe(static _ => { }, ex => captured = ex, static () => { });
173+
174+
await Assert.That(captured).IsSameReferenceAs(expected);
175+
}
176+
177+
/// <summary>Tests that the parameterless action overload runs the action and completes.</summary>
178+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
179+
[Test]
180+
public async Task FromAsyncWithAllNotificationsRunsAction()
181+
{
182+
var source = ObservableMixins.FromAsyncWithAllNotifications(static _ => Task.CompletedTask);
183+
184+
var result = await RunToCompletionAsync(source);
185+
186+
await Assert.That(result).IsEqualTo(RxVoid.Default);
187+
}
188+
189+
/// <summary>Tests that the parameterized action overload passes the parameter and completes.</summary>
190+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
191+
[Test]
192+
public async Task FromAsyncWithAllNotificationsWithParameterRunsAction()
193+
{
194+
const int Parameter = 7;
195+
var observed = 0;
196+
197+
var source = ObservableMixins.FromAsyncWithAllNotifications(
198+
(param, _) =>
199+
{
200+
observed = param;
201+
return Task.CompletedTask;
202+
},
203+
Parameter);
204+
205+
_ = await RunToCompletionAsync(source);
206+
207+
await Assert.That(observed).IsEqualTo(Parameter);
208+
}
209+
210+
/// <summary>Tests that the result-producing overload emits the produced value.</summary>
211+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
212+
[Test]
213+
public async Task FromAsyncWithAllNotificationsProducesResult()
214+
{
215+
const int Expected = 42;
216+
217+
var source = ObservableMixins.FromAsyncWithAllNotifications(static _ => Task.FromResult(Expected));
218+
219+
var result = await RunToCompletionAsync(source);
220+
221+
await Assert.That(result).IsEqualTo(Expected);
222+
}
223+
224+
/// <summary>Tests that the parameterized result-producing overload emits the produced value.</summary>
225+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
226+
[Test]
227+
public async Task FromAsyncWithAllNotificationsWithParameterProducesResult()
228+
{
229+
const int Parameter = 21;
230+
const int Multiplier = 2;
231+
const int Expected = 42;
232+
233+
var source = ObservableMixins.FromAsyncWithAllNotifications(
234+
static (param, _) => Task.FromResult(param * Multiplier),
235+
Parameter);
236+
237+
var result = await RunToCompletionAsync(source);
238+
239+
await Assert.That(result).IsEqualTo(Expected);
240+
}
241+
242+
/// <summary>Tests that a faulted asynchronous action surfaces its exception as an <c>OnError</c> notification.</summary>
243+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
244+
[Test]
245+
public async Task FromAsyncWithAllNotificationsPropagatesError()
246+
{
247+
var expected = new InvalidOperationException("async failure");
248+
249+
var source = ObservableMixins.FromAsyncWithAllNotifications(
250+
static (ex, _) => Task.FromException<int>(ex),
251+
expected);
252+
253+
var (result, _) = Materialize(source);
254+
255+
var completion = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
256+
using var subscription = result.Subscribe(
257+
static _ => { },
258+
ex => completion.TrySetResult(ex),
259+
static () => { });
260+
261+
var actual = await completion.Task;
262+
263+
await Assert.That(actual).IsSameReferenceAs(expected);
264+
}
265+
266+
/// <summary>Tests that the cancel delegate returned alongside the result can be invoked without throwing.</summary>
267+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
268+
[Test]
269+
public async Task FromAsyncWithAllNotificationsCancelDelegateIsInvokable()
270+
{
271+
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
272+
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
273+
274+
var source = ObservableMixins.FromAsyncWithAllNotifications(
275+
static async (state, ct) =>
276+
{
277+
var (start, rel) = state;
278+
_ = start.TrySetResult();
279+
await rel.Task.ConfigureAwait(false);
280+
ct.ThrowIfCancellationRequested();
281+
return 0;
282+
},
283+
(started, release));
284+
285+
var (result, cancel) = Materialize(source);
286+
287+
var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
288+
using var subscription = result.Subscribe(
289+
static _ => { },
290+
_ => completion.TrySetResult(),
291+
() => completion.TrySetResult());
292+
293+
await started.Task;
294+
cancel();
295+
_ = release.TrySetResult();
296+
297+
await completion.Task;
298+
299+
await Assert.That(completion.Task.IsCompletedSuccessfully).IsTrue();
300+
}
301+
302+
/// <summary>Subscribes to a deferred source and returns the single tuple it emits synchronously on subscription.</summary>
303+
/// <typeparam name="TResult">The result type produced by the inner observable.</typeparam>
304+
/// <param name="source">The deferred source to materialize.</param>
305+
/// <returns>The result observable and its cancellation delegate.</returns>
306+
private static (IObservable<TResult> Result, Action Cancel) Materialize<TResult>(
307+
IObservable<(IObservable<TResult> Result, Action Cancel)> source)
308+
{
309+
(IObservable<TResult> Result, Action Cancel)? captured = null;
310+
using var subscription = source.Subscribe(tuple => captured = tuple);
311+
312+
return captured ?? throw new InvalidOperationException("The deferred source did not emit a value synchronously.");
313+
}
314+
315+
/// <summary>Runs a deferred asynchronous source to completion and returns the single emitted result.</summary>
316+
/// <typeparam name="TResult">The result type produced by the inner observable.</typeparam>
317+
/// <param name="source">The deferred source to run.</param>
318+
/// <returns>The single value emitted by the inner observable.</returns>
319+
private static async Task<TResult> RunToCompletionAsync<TResult>(
320+
IObservable<(IObservable<TResult> Result, Action Cancel)> source)
321+
{
322+
var (result, _) = Materialize(source);
323+
324+
var completion = new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously);
325+
var last = default(TResult)!;
326+
using var subscription = result.Subscribe(
327+
value => last = value,
328+
ex => completion.TrySetException(ex),
329+
() => completion.TrySetResult(last));
330+
331+
return await completion.Task;
332+
}
333+
99334
/// <summary>Test class for reference type testing.</summary>
100335
private sealed class TestClass
101336
{

0 commit comments

Comments
 (0)
⌂ 换网址