|
| 1 | +// Copyright (c) usercode |
| 2 | +// https://github.com/usercode/DragonFly |
| 3 | +// MIT License |
| 4 | + |
| 5 | +using System.Runtime.CompilerServices; |
| 6 | + |
| 7 | +namespace DragonFly; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// AsyncLazy |
| 11 | +/// </summary> |
| 12 | +/// <typeparam name="T"></typeparam> |
| 13 | +public class AsyncLazy<T> |
| 14 | +{ |
| 15 | + public AsyncLazy(ContentReference reference, Func<Task<T?>> taskFactory) |
| 16 | + { |
| 17 | + ContentReference = reference; |
| 18 | + _lazy = new Lazy<Task<T?>>(taskFactory); |
| 19 | + } |
| 20 | + |
| 21 | + public AsyncLazy(T? value) |
| 22 | + { |
| 23 | + SetDirectValue(value); |
| 24 | + } |
| 25 | + |
| 26 | + private Lazy<Task<T?>> _lazy; |
| 27 | + public ContentReference? ContentReference { get; private set; } |
| 28 | + private T? _directValue; |
| 29 | + private bool _directValueChanged; |
| 30 | + |
| 31 | + public TaskAwaiter<T?> GetAwaiter() |
| 32 | + { |
| 33 | + return _lazy.Value.GetAwaiter(); |
| 34 | + } |
| 35 | + |
| 36 | + public void SetDirectValue(T? value) |
| 37 | + { |
| 38 | + if (value is ContentItem content) |
| 39 | + { |
| 40 | + ContentReference = content.ToReference(); |
| 41 | + } |
| 42 | + else if (value is Asset asset) |
| 43 | + { |
| 44 | + ContentReference = asset.ToReference(); |
| 45 | + } |
| 46 | + else |
| 47 | + { |
| 48 | + ContentReference = null; |
| 49 | + } |
| 50 | + |
| 51 | + _directValue = value; |
| 52 | + _directValueChanged = true; |
| 53 | + |
| 54 | + _lazy = new Lazy<Task<T?>>(() => Task.FromResult(value)); |
| 55 | + } |
| 56 | + |
| 57 | + public bool TryGetDirectValue(out T? value) |
| 58 | + { |
| 59 | + if (_directValueChanged) |
| 60 | + { |
| 61 | + value = _directValue; |
| 62 | + |
| 63 | + return true; |
| 64 | + } |
| 65 | + |
| 66 | + value = default; |
| 67 | + |
| 68 | + return false; |
| 69 | + } |
| 70 | + |
| 71 | + public static implicit operator AsyncLazy<T>(T? value) |
| 72 | + { |
| 73 | + return new AsyncLazy<T>(value); |
| 74 | + } |
| 75 | +} |
0 commit comments