Disposable View Model
Overview
DisposableViewModel extends ViewModelBase by adding essential tools for resource management: a CancellationToken and a CompositeDisposable container. It is designed to simplify the cleanup of subscriptions, timers, and asynchronous operations.
Core Components
CompositeDisposable
The Disposable property is a thread-safe container for any IDisposable objects. Instead of manually disposing of every field in the Dispose method, you can simply "register" them.
How to use: Use the
.DisposeItWith(Disposable)extension method on your subscriptions or resources.Behavior: When the ViewModel is disposed, the container automatically disposes of all registered resources in the order they were added.
CancellationToken
The DisposeCancel property provides a CancellationToken that is automatically triggered when the ViewModel starts its disposal process.
Thread-Safety: The cancellation and disposal of the source are handled in a thread-safe manner.
Primary Use Case: Passing the token to asynchronous tasks, background loops, or observable subscriptions to ensure they stop immediately when the ViewModel is destroyed.
Disposal Logic
DisposableViewModel overrides the Dispose(bool disposing) method to ensure a clean teardown. The process follows a specific order:
Cancel: The
CancellationTokenis canceled, notifying all linked tasks to stop.Dispose Source: The
CancellationTokenSourceitself is disposed.Dispose Resources: The
CompositeDisposablecontainer is disposed, which in turn disposes of all registered objects.
API
DisposableViewModel
Represents a base view model that supports disposable resources and cancellation handling. This class ensures proper cleanup of resources when the view model is disposed.
Property | Type | Description |
|---|---|---|
|
| Gets a cancellation token that is linked to the disposal state of the view model. If the view model is disposed, the token is set to |
|
| Gets a |
Method | Return Type | Description |
|---|---|---|
|
| Releases unmanaged resources and cancels any pending operations when disposing. |
DisposableViewModel.Dispose(bool disposing)
Parameter | Type | Description |
|---|---|---|
|
|
|