Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 29 additions & 13 deletions src/ReactiveUI.Binding.Shared/Fallback/RuntimeBindingFallback.cs
Original file line number Diff line number Diff line change
Expand Up @@ -448,17 +448,25 @@ private static ReactiveBinding<TView, BindingChange> TwoWayBinding<TViewModel, T
where TView : IViewFor
{
var toViewWrite = Write(toView, view, viewProperty, bindingExpression);
var toViewModelWrite = WriteViewModel(fromView, view, viewModel, viewModelProperty, bindingExpression);
try
{
var toViewModelWrite = WriteViewModel(fromView, view, viewModel, viewModelProperty, bindingExpression);

var changed = new MergeSignal<BindingChange>(
new MapSignal<TViewProp, BindingChange>(toView, static v => new BindingChange(v, true)),
new MapSignal<TViewModelProp, BindingChange>(fromView, static v => new BindingChange(v, false)));
var changed = new MergeSignal<BindingChange>(
new MapSignal<TViewProp, BindingChange>(toView, static v => new BindingChange(v, true)),
new MapSignal<TViewModelProp, BindingChange>(fromView, static v => new BindingChange(v, false)));

return new(
view,
changed,
BindingDirection.TwoWay,
new MultipleDisposable(toViewWrite, toViewModelWrite));
return new(
view,
changed,
BindingDirection.TwoWay,
new MultipleDisposable(toViewWrite, toViewModelWrite));
}
catch
{
toViewWrite.Dispose();
throw;
}
}

/// <summary>Wraps a one-way write as the binding value the view-first APIs hand back.</summary>
Expand Down Expand Up @@ -558,11 +566,19 @@ private static MultipleDisposable JoinBothDirections<TSource, TTarget, TSourcePr
{
var toTarget = Write(forward, target, targetProperty, bindingExpression);

// The target's own current value is not a change the source asked for, so it is dropped rather
// than written straight back over the value that just seeded it.
var toSource = Write(reverse.Skip(1), source, sourceProperty, bindingExpression);
try
{
// The target's own current value is not a change the source asked for, so it is dropped rather
// than written straight back over the value that just seeded it.
var toSource = Write(reverse.Skip(1), source, sourceProperty, bindingExpression);

return new(toTarget, toSource);
return new(toTarget, toSource);
}
catch
{
toTarget.Dispose();
throw;
}
}

/// <summary>Delivers a sequence of values onto a property of the written object.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ private static void EmitTwoWaySubscription(
TargetParameterName,
inv.TargetPropertyPath,
inv.TargetExpressionText);
_ = sb.Try();
BindingEmitterHelpers.AppendWriteSubscription(
sb.BlankLine().BeginVar("d2"),
targetVar,
Expand All @@ -157,6 +158,12 @@ private static void EmitTwoWaySubscription(
_ = sb.BlankLine()
.Return($"new {GeneratedTypeNames.MultipleDisposable}(d1, d2)")
.CloseBlock()
.Line("catch")
.OpenBlock()
.Line("d1.Dispose();")
.Line("throw;")
.CloseBlock()
.CloseBlock()
.BlankLine();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -286,14 +286,15 @@ private static void AppendProperty(SourceWriter sb, ObservableAsPropertyInfo pro
.BlankLine()
.Append(property.Modifiers).Append(' ').Append(property.TypeFullName).Append(' ').Append(name).Append(" => ");

// A source that produces a value as it is subscribed raises the property's notifications before the helper is
// assigned, and a listener reading the property then asks the starting helper for its value.
_ = AppendFieldName(sb, name).Append("Helper is null ? ").Append(HelperType).Append('<').Append(property.TypeFullName)
// Notifications can run before a replacement helper is assigned, so the starting helper takes precedence
// over the field even when that field holds a helper from an earlier activation.
_ = sb.Append(HelperType).Append('<').Append(property.TypeFullName)
.Append(">.PendingValue(this, ").AppendQuoted(name).Append(", ");
_ = AppendFieldName(sb, name).Append("Helper is null ? ");
_ = property.StoresInitialValue
? AppendFieldName(sb, name)
: sb.Append(property.InitialValue ?? "default!");
_ = AppendFieldName(sb.Append(") : "), name).Line("Helper.Value;");
_ = AppendFieldName(sb.Append(" : "), name).Line("Helper.Value);");
}

/// <summary>Appends a field name for a property, <c>_{name}</c> with the first letter lowered, without building a string for it.</summary>
Expand Down
26 changes: 26 additions & 0 deletions src/examples/Documentation/Pages/bindings/BindingErrorExamples.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,32 @@ public static void SetterThatThrowsReachesTheCaller()
// A statement reference has at most 18 characters. (Parameter 'value')
}

/// <summary>A reverse converter that fails during setup leaves the source disconnected.</summary>
public static void FailedTwoWayBindingReleasesTheSource()
{
TransferDraft draft = new() { Reference = ShortReference };
Label label = new();

try
{
using IDisposable binding = draft.BindTwoWay(
label,
x => x.Reference,
x => x.Text,
static reference => reference,
static reference => throw new InvalidOperationException(ConversionMessage, new FormatException(CauseMessage)));
}
catch (TargetInvocationException)
{
draft.Reference = AprilReference;
Console.WriteLine(label.Text == ShortReference);
}

// Output:
// LogHost: x => x.Reference Binding received an Exception! (OnError)
// True
}

/// <summary>Applies the fault contract directly with <see cref="BindingErrors.Subscribe{T}"/>: values reach the write, and each kind of fault is handled as a binding handles it.</summary>
public static void SubscribeAppliesTheFaultContract()
{
Expand Down
2 changes: 2 additions & 0 deletions src/examples/Documentation/Pages/bindings/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,8 @@

BindingErrorExamples.SetterThatThrowsReachesTheCaller();

BindingErrorExamples.FailedTwoWayBindingReleasesTheSource();

BindingErrorExamples.SubscribeAppliesTheFaultContract();

await BindingHookExamples.BindWithoutHook();
Expand Down
2 changes: 1 addition & 1 deletion src/examples/Documentation/Pages/bindings/bindings.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net10.0</TargetFrameworks>
<TargetFrameworks>net10.0;net11.0</TargetFrameworks>
<UseMaui>true</UseMaui>
<LangVersion>14.0</LangVersion>
<RootNamespace>ReactiveUI.Binding.Documentation</RootNamespace>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
// ReactiveUI and Contributors licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.

using System.ComponentModel;
using ReactiveUI.Binding.Documentation.Todo;
using ReactiveUI.Primitives.Signals;

namespace ReactiveUI.Binding.Documentation.Properties;

/// <summary>Shows a partial property declared with <see cref="ObservableAsPropertyAttribute"/>.</summary>
public static class ObservableAsPropertyAttributeExamples
public static partial class ObservableAsPropertyAttributeExamples
{
/// <summary>Constructs <see cref="SummaryViewModel"/> and reads both of its generated properties.</summary>
public static void DeclareAPropertyWithTheAttribute()
Expand Down Expand Up @@ -37,4 +38,44 @@ public static void StartFromAnInitialValue()
// Loading
// Ready
}

/// <summary>Reads each replacement helper's value from its synchronous change notification.</summary>
public static void ReplaceAHelperWhileObserved()
{
using ReplaceableStatus? status = new();
string? observed = null;
status.PropertyChanged += (_, _) => observed = status.Status;

status.Connect(Signal.Return("Connected"));
Console.WriteLine(observed);
status.Connect(Signal.Return("Disconnected"));
Console.WriteLine(observed);

// Output:
// Connected
// Disconnected
}

/// <summary>Replaces its property's source when a new connection starts.</summary>
[System.Diagnostics.DebuggerDisplay("Status = {Status}")]
public sealed partial class ReplaceableStatus : INotifyPropertyChanged, IDisposable
{
/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged;

/// <summary>Gets the latest value from the current connection.</summary>
[ObservableAsProperty]
public partial string? Status { get; }

/// <summary>Disposes the previous helper and follows a new source.</summary>
/// <param name="source">The connection's status values.</param>
public void Connect(IObservable<string?> source)
{
_statusHelper?.Dispose();
_statusHelper = source.ToProperty(this, static x => x.Status);
}

/// <inheritdoc/>
public void Dispose() => _statusHelper?.Dispose();
}
}
2 changes: 2 additions & 0 deletions src/examples/Documentation/Pages/properties/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@
ObservableAsPropertyAttributeExamples.DeclareAPropertyWithTheAttribute();

ObservableAsPropertyAttributeExamples.StartFromAnInitialValue();

ObservableAsPropertyAttributeExamples.ReplaceAHelperWhileObserved();
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net10.0</TargetFrameworks>
<TargetFrameworks>net10.0;net11.0</TargetFrameworks>
<UseMaui>true</UseMaui>
<LangVersion>14.0</LangVersion>
<RootNamespace>ReactiveUI.Binding.Documentation</RootNamespace>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved.
// ReactiveUI and Contributors licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.

using System.ComponentModel;

namespace ReactiveUI.Binding.GeneratedCode.Tests.Binding;

/// <summary>Checks that failed binding creation releases every attached notification handler.</summary>
public class BindTwoWaySubscriptionTests
{
/// <summary>The value delivered before reverse subscription setup.</summary>
private const string InitialText = "initial";

/// <summary>The edit that must not cross a failed binding.</summary>
private const string LaterText = "after failure";

/// <summary>A failure on either endpoint leaves neither endpoint bound.</summary>
/// <param name="rejectSource">Whether the source, rather than the target, rejects the subscription.</param>
/// <param name="withConverters">Whether to use explicit conversion functions.</param>
/// <returns>The asynchronous assertion operation.</returns>
[Test]
[MatrixDataSource]
public async Task BindTwoWay_SubscriptionThrows_DetachesBothEndpoints([Matrix(false, true)] bool rejectSource, [Matrix(false, true)] bool withConverters)
{
var source = new Endpoint { Text = InitialText, RejectSubscription = rejectSource };
var target = new Endpoint { RejectSubscription = !rejectSource };

var createBinding = withConverters
? (Func<IDisposable>)(() => source.BindTwoWay(target, x => x.Text, x => x.Text, static value => value, static value => value))
: () => source.BindTwoWay(target, x => x.Text, x => x.Text);

await Assert.That(createBinding).Throws<InvalidOperationException>();

await Assert.That(source.HasSubscribers).IsFalse();
await Assert.That(target.HasSubscribers).IsFalse();
var textAfterFailure = target.Text;
source.Text = LaterText;
await Assert.That(target.Text).IsEqualTo(textAfterFailure);
}

/// <summary>A failed runtime binding also releases the forward subscription.</summary>
/// <param name="withConverters">Whether to use explicit conversion functions.</param>
/// <returns>The asynchronous assertion operation.</returns>
[Test]
[Arguments(false)]
[Arguments(true)]
public async Task BindTwoWayUnsafe_TargetSubscriptionThrows_DetachesSource(bool withConverters)
{
var source = new Endpoint { Text = InitialText };
var target = new Endpoint { RejectSubscription = true };

var createBinding = withConverters
? (Func<IDisposable>)(() => source.BindTwoWayUnsafe(target, x => x.Text, x => x.Text, static value => value, static value => value))
: () => source.BindTwoWayUnsafe(target, x => x.Text, x => x.Text);

await Assert.That(createBinding).Throws<InvalidOperationException>();

await Assert.That(source.HasSubscribers).IsFalse();
source.Text = LaterText;
await Assert.That(target.Text).IsEqualTo(InitialText);
}

/// <summary>A failed view-first runtime binding releases its view-model subscription.</summary>
/// <returns>The asynchronous assertion operation.</returns>
[Test]
public async Task BindUnsafe_TargetSubscriptionThrows_DetachesSource()
{
var source = new Endpoint { Text = InitialText };
var target = new Endpoint { RejectSubscription = true };

await Assert.That(() => target.BindUnsafe(source, x => x.Text, x => x.Text))
.Throws<InvalidOperationException>();

await Assert.That(source.HasSubscribers).IsFalse();
source.Text = LaterText;
await Assert.That(target.Text).IsEqualTo(InitialText);
}

/// <summary>An endpoint that can reject notification subscriptions before attaching them.</summary>
public sealed class Endpoint : INotifyPropertyChanged, IViewFor
{
/// <summary>The handlers attached to this endpoint.</summary>
private PropertyChangedEventHandler? _handlers;

/// <inheritdoc/>
public event PropertyChangedEventHandler? PropertyChanged
{
add
{
if (RejectSubscription)
{
throw new InvalidOperationException("The endpoint rejected the subscription.");
}

_handlers += value;
}

remove => _handlers -= value;
}

/// <inheritdoc/>
public object? ViewModel { get; set; }

/// <summary>Gets or sets a value indicating whether notification subscriptions fail.</summary>
public bool RejectSubscription { get; set; }

/// <summary>Gets a value indicating whether any notification handler remains attached.</summary>
public bool HasSubscribers => _handlers is not null;

/// <summary>Gets or sets the value synchronized by the binding.</summary>
public string Text
{
get;
set
{
if (field == value)
{
return;
}

field = value;
_handlers?.Invoke(this, new(nameof(Text)));
}
} = string.Empty;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,22 @@ public async Task HelperAssignedAfterListenerAttaches_ListenerReadsTheValue()
await Assert.That(vm.Shown).IsTrue();
}

/// <summary>Replacing a helper exposes the new value during notifications, before the helper field is reassigned.</summary>
/// <returns>A task representing the asynchronous test operation.</returns>
[Test]
public async Task HelperReassigned_ListenerReadsTheNewValue()
{
var vm = new StartupViewModel();
vm.Show(new BehaviorSubject<bool>(true));
var read = new List<bool>();
vm.PropertyChanged += (_, _) => read.Add(vm.Shown);

vm.Show(new BehaviorSubject<bool>(false));

await Assert.That(read[^1]).IsFalse();
await Assert.That(vm.Shown).IsFalse();
}

/// <summary>
/// A property created first that follows one created second sees the second's value as it starts, since reading it
/// from the notification finds the value (ReactiveUI #4541).
Expand Down
Loading
Loading