/
ObservableAsPropertyExtensions.cs
80 lines (70 loc) · 3.1 KB
/
ObservableAsPropertyExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
using System.Linq.Expressions;
using System.Reactive.Concurrency;
using System.Reflection;
namespace ReactiveUI.Fody.Helpers
{
/// <summary>
/// Extension methods for observable as property helpers.
/// </summary>
public static class ObservableAsPropertyExtensions
{
/// <summary>
/// To the property execute.
/// </summary>
/// <typeparam name="TObj">The type of the object.</typeparam>
/// <typeparam name="TRet">The type of the ret.</typeparam>
/// <param name="item">The observable with the return value.</param>
/// <param name="source">The source.</param>
/// <param name="property">The property.</param>
/// <param name="initialValue">The initial value.</param>
/// <param name="deferSubscription">if set to <c>true</c> [defer subscription].</param>
/// <param name="scheduler">The scheduler.</param>
/// <returns>An observable property helper with the specified return value.</returns>
/// <exception cref="Exception">
/// Could not resolve expression " + property + " into a property.
/// or
/// Backing field not found for " + propertyInfo.
/// </exception>
public static ObservableAsPropertyHelper<TRet> ToPropertyEx<TObj, TRet>(this IObservable<TRet> item, TObj source, Expression<Func<TObj, TRet>> property, TRet initialValue = default, bool deferSubscription = false, IScheduler scheduler = null)
where TObj : ReactiveObject
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
var result = item.ToProperty(source, property, initialValue, deferSubscription, scheduler);
// Now assign the field via reflection.
var propertyInfo = property.GetPropertyInfo();
if (propertyInfo == null)
{
throw new Exception("Could not resolve expression " + property + " into a property.");
}
var field = propertyInfo.DeclaringType.GetTypeInfo().GetDeclaredField("$" + propertyInfo.Name);
if (field == null)
{
throw new Exception("Backing field not found for " + propertyInfo);
}
field.SetValue(source, result);
return result;
}
private static PropertyInfo GetPropertyInfo(this LambdaExpression expression)
{
var current = expression.Body;
if (current is UnaryExpression unary)
{
current = unary.Operand;
}
var call = (MemberExpression)current;
return (PropertyInfo)call.Member;
}
}
}