diff --git a/src/WindreamHub.Legacy.Client/Models/ModelExtensions.cs b/src/WindreamHub.Legacy.Client/Models/ModelExtensions.cs index 630c774..3c61b3a 100644 --- a/src/WindreamHub.Legacy.Client/Models/ModelExtensions.cs +++ b/src/WindreamHub.Legacy.Client/Models/ModelExtensions.cs @@ -1,8 +1,8 @@ using DigitalData.Core.Legacy.Client; using System; using System.Net.Http; +using System.Threading; using System.Threading.Tasks; -using static System.Net.Mime.MediaTypeNames; namespace WindreamHub.Legacy.Client.Models { @@ -16,13 +16,78 @@ namespace WindreamHub.Legacy.Client.Models return new SimplifiedResponse(ok: message.IsSuccessStatusCode, status: message.StatusCode, data: data, error: err); } - public static async Task Subscribe(this Task> responseAsync, Action next, Action error) + public static async Task SubscribeAsync(this Task> responseAsync, Action next, Action error, CancellationToken cancellationToken = default) { + if (cancellationToken.IsCancellationRequested) + return; + var res = await responseAsync; if (res.Ok) next(res.Data); else error(res.Error); } + + public static void Subscribe(this Task> responseAsync, Action next, Action error, CancellationToken cancellationToken = default) + { + Task.Run(async () => + { + if (cancellationToken.IsCancellationRequested) + return; + + var res = await responseAsync; + if (res.Ok) + next(res.Data); + else + error?.Invoke(res.Error); + }); + } + + public static void Subscribe(this Task> responseAsync, int millisecondsDelay, Action next, Action error = null, CancellationToken cancellationToken = default) + { + Task.Run(async () => + { + while (!cancellationToken.IsCancellationRequested) + { + var res = await responseAsync; + if (res.Ok) + next(res.Data); + else + error?.Invoke(res.Error); + + await Task.Delay(millisecondsDelay, cancellationToken); + } + }); + } + + public static Func CreateSubscribeAsyncAction(this Task> responseAsync, Action next, Action error = null, CancellationToken cancellationToken = default) + { + return async () => + { + if (cancellationToken.IsCancellationRequested) + return; + + var res = await responseAsync; + if (res.Ok) + next(res.Data); + else + error?.Invoke(res.Error); + }; + } + + public static Action CreateSubscribeAction(this Task> responseAsync, Action next, Action error = null, CancellationToken cancellationToken = default) + { + return () => Task.Run(async () => + { + if (cancellationToken.IsCancellationRequested) + return; + + var res = await responseAsync; + if (res.Ok) + next(res.Data); + else + error?.Invoke(res.Error); + }); + } } } \ No newline at end of file