Created
February 25, 2018 02:40
-
-
Save codebeaulieu/8e668152fd1b12565ed6f320b53a987c to your computer and use it in GitHub Desktop.
ViewModelBase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1 | |
public abstract class ViewModelBase<T> : ReactiveObject, IDisposable where T : ReactiveObject, IDisposable | |
{ | |
// 2 | |
protected readonly Lazy<CompositeDisposable> ViewModelBindings = new Lazy<CompositeDisposable>(() => new CompositeDisposable()); | |
// 3 | |
public bool IsDisposed { get; private set; } | |
bool _bindingsRegistered; | |
[DataMember] | |
public bool BindingsRegistered | |
{ | |
get { return _bindingsRegistered; } | |
protected set { this.RaiseAndSetIfChanged(ref _bindingsRegistered, value); } | |
} | |
// 4 | |
protected abstract void RegisterObservables(); | |
// 5 | |
protected virtual void Initialize() { } | |
// 6 | |
protected ViewModelBase() | |
{ | |
Initialize(); | |
RegisterObservables(); | |
} | |
// 7 | |
public void RegisterBindings() | |
{ | |
if (!BindingsRegistered) | |
{ | |
RegisterObservables(); | |
BindingsRegistered = true; | |
} | |
} | |
// 8 | |
public void UnregisterBindings() | |
{ | |
if (ViewModelBindings?.IsValueCreated ?? false) | |
ViewModelBindings?.Value?.Clear(); | |
BindingsRegistered = false; | |
} | |
#region IDisposable implementation | |
// 9 | |
public void Dispose() | |
{ | |
Dispose(true); | |
GC.SuppressFinalize(true); | |
} | |
// 10 | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (disposing && !IsDisposed) | |
{ | |
IsDisposed = true; | |
if (ViewModelBindings?.IsValueCreated ?? false) | |
ViewModelBindings?.Value?.Dispose(); | |
} | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment