DEV Community

loading...

How to use CanellationToken With ICommand A Solid Implementation of ICommand

Ahmed Fouad
I am a full stack .net dev ,FP antisuaste and currently i am writting some articles about fp using .net framework
Originally published at Medium on ・1 min read

This article can be considered a part 2 of Async Command A Modern Implementation of ICommand in which we were addressing the async problem in ICommand by blocking the CanExecuteStatus to false in case the previous task was not yet completed.

In this article, we will address the same problem using a different way we will use CancellationToken to cancel the pending task and execute the new one, imagine you have a news app where the user should click on one title in a listview the app will download the news article and will show it, what happens when the user clicks on a title and before the download complete he clicks on another one.

And you can use it in your ViewModel like this

CommandAsync<Uri> commandAsync = new CommandAsync<Uri>(async (uri,cancellationToken)=>await client.GetAsync(uri,cancellationToken));

or can be simplified to this

CommandAsync<Uri> commandAsync = new CommandAsync<Uri>(httpclient.GetAsync);

Discussion (0)

Forem Open with the Forem app