In my MVVM application, when a ViewModel gets activated, a Task gets started that establishes a network connection and could take some time to complete. This Task is cancalable:
private async Task ConnectAsync(CancellationToken cancellationToken = default)
{
...
}
I'm using IActivatableViewModel to start it on ViewModel-activation like that:
// Constructor:
public SomeViewModel(...)
{
this.WhenActivated(disposable => {
Observable.StartAsync(ConnectAsync);
});
}
Now what is the recommended method to cancel this long-running Task when the ViewModel gets deactivated before the Task completes?
I came up with this:
this.WhenActivated(disposable => {
Observable.StartAsync(ConnectAsync).Subscribe().DisposeWith(disposable);
});
Is this the right solution or is there a better one?
Thank you in advance!