Skip to content

Applies to

net10.0, net10.0-browserwasm1.0, net10.0-desktop1.0, net9.0, net9.0-browserwasm1.0, net9.0-desktop1.0, net8.0, net8.0-ios17.5, net8.0-maccatalyst17.5, net8.0-macos14.2, net8.0-macos14.5, net8.0-tvos17.2, netstandard2.1, net462, net481

public static IObservableAsync<T> Using<T, TResource>(Func<CancellationToken, ValueTask<TResource>> resourceFactory, Func<TResource, IObservableAsync<T>> observableFactory) where TResource : IAsyncDisposable

View source

Summary: Creates an observable sequence that manages the lifetime of an asynchronous resource, ensuring the resource is disposed when the sequence terminates.

Type parameters

NameDescription
TThe type of the elements produced by the observable sequence.
TResourceThe type of the asynchronous resource that implements IAsyncDisposable.

Parameters

NameTypeDescription
resourceFactoryFunc>A function that asynchronously creates the resource to be used by the observable sequence. The function receives a CancellationToken and returns a ValueTask representing the asynchronous creation of the resource.
observableFactoryFunc>A function that, given the created resource, returns an [ObservableAsync](# representing the observable sequence that uses the resource.

Returns: IObservableAsync -- An ObservableAsync that uses the specified resource and ensures the resource is disposed asynchronously when the sequence completes or an error occurs.

Remarks

The resource is created for each subscription and is disposed asynchronously when the observable sequence terminates, either by completion or error. If the observable factory throws an exception, the resource is disposed before the exception is propagated. This method is useful for managing resources that must be disposed when no longer needed, such as streams or database connections, in conjunction with asynchronous observable sequences.