Asv.Avalonia.Docs Help

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:

  1. Cancel: The CancellationToken is canceled, notifying all linked tasks to stop.

  2. Dispose Source: The CancellationTokenSource itself is disposed.

  3. Dispose Resources: The CompositeDisposable container 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

DisposeCancel

CancellationToken

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 CancellationToken.None.

Disposable

CompositeDisposable

Gets a CompositeDisposable collection for managing disposable resources. This ensures that all registered disposables are cleaned up when the view model is disposed.

Method

Return Type

Description

Dispose(bool disposing)

void

Releases unmanaged resources and cancels any pending operations when disposing.

DisposableViewModel.Dispose(bool disposing)

Parameter

Type

Description

disposing

bool

true if disposing managed resources; otherwise, false.

Last modified: 18 January 2026