11using System . ComponentModel ;
22using System . Diagnostics . CodeAnalysis ;
33using System . Linq . Expressions ;
4+ using System . Reactive . Disposables ;
45using System . Reactive . Linq ;
56using System . Reflection ;
67using System . Text . Json ;
@@ -163,7 +164,7 @@ public void Transaction<TValue>(Expression<Func<Settings, TValue>> expression, T
163164 }
164165
165166 /// <inheritdoc />
166- public void RelayPropertyFor < T , TValue > (
167+ public IDisposable RelayPropertyFor < T , TValue > (
167168 T source ,
168169 Expression < Func < T , TValue > > sourceProperty ,
169170 Expression < Func < Settings , TValue > > settingsProperty ,
@@ -181,7 +182,7 @@ public void RelayPropertyFor<T, TValue>(
181182 var sourceTypeName = source . GetType ( ) . Name ;
182183
183184 // Update source when settings change
184- SettingsPropertyChanged += ( sender , args ) =>
185+ void OnSettingsPropertyChanged ( object ? sender , RelayPropertyChangedEventArgs args )
185186 {
186187 if ( args . PropertyName != settingsPropertyPath )
187188 return ;
@@ -198,10 +199,10 @@ public void RelayPropertyFor<T, TValue>(
198199 ) ;
199200
200201 sourceInstanceAccessor . Set ( source , settingsAccessor . Get ( Settings ) ) ;
201- } ;
202+ }
202203
203204 // Set and Save settings when source changes
204- source . PropertyChanged += ( sender , args ) =>
205+ void OnSourcePropertyChanged ( object ? sender , PropertyChangedEventArgs args )
205206 {
206207 if ( args . PropertyName != sourcePropertyPath )
207208 return ;
@@ -241,13 +242,32 @@ public void RelayPropertyFor<T, TValue>(
241242 sender ,
242243 new RelayPropertyChangedEventArgs ( settingsPropertyPath , true )
243244 ) ;
244- } ;
245+ }
246+
247+ var subscription = Disposable . Create ( ( ) =>
248+ {
249+ source . PropertyChanged -= OnSourcePropertyChanged ;
250+ SettingsPropertyChanged -= OnSettingsPropertyChanged ;
251+ } ) ;
245252
246- // Set initial value if requested
247- if ( setInitial )
253+ try
248254 {
249- sourceInstanceAccessor . Set ( settingsAccessor . Get ( Settings ) ) ;
255+ SettingsPropertyChanged += OnSettingsPropertyChanged ;
256+ source . PropertyChanged += OnSourcePropertyChanged ;
257+
258+ // Set initial value if requested
259+ if ( setInitial )
260+ {
261+ sourceInstanceAccessor . Set ( settingsAccessor . Get ( Settings ) ) ;
262+ }
250263 }
264+ catch
265+ {
266+ subscription . Dispose ( ) ;
267+ throw ;
268+ }
269+
270+ return subscription ;
251271 }
252272
253273 /// <inheritdoc />
0 commit comments