using System; using System.Threading.Tasks; using JetBrains.Annotations; namespace Kyoo { /// /// A class containing helper method for tasks. /// public static class TaskUtils { /// /// Run a method after the execution of the task. /// /// The task to wait. /// /// The method to run after the task finish. This will only be run if the task finished successfully. /// /// The type of the item in the task. /// A continuation task wrapping the initial task and adding a continuation method. /// /// The source task has been canceled. public static Task Then(this Task task, Action then) { return task.ContinueWith(x => { if (x.IsFaulted) x.Exception!.InnerException!.ReThrow(); if (x.IsCanceled) throw new TaskCanceledException(); then(x.Result); return x.Result; }, TaskContinuationOptions.ExecuteSynchronously); } /// /// Map the result of a task to another result. /// /// The task to map. /// The mapper method, it take the task's result as a parameter and should return the new result. /// The type of returns of the given task /// The resulting task after the mapping method /// A task wrapping the initial task and mapping the initial result. /// The source task has been canceled. public static Task Map(this Task task, Func map) { return task.ContinueWith(x => { if (x.IsFaulted) x.Exception!.InnerException!.ReThrow(); if (x.IsCanceled) throw new TaskCanceledException(); return map(x.Result); }, TaskContinuationOptions.ExecuteSynchronously); } /// /// A method to return the a default value from a task if the initial task is null. /// /// The initial task /// The type that the task will return /// A non-null task. [NotNull] public static Task DefaultIfNull([CanBeNull] Task value) { return value ?? Task.FromResult(default); } } }