Welcome to mirror list, hosted at ThFree Co, Russian Federation.

AsyncValue.cs « Xamarin.PropertyEditing - github.com/xamarin/Xamarin.PropertyEditing.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 567c57091a8781446aff3f424f117c8db422ff6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

namespace Xamarin.PropertyEditing
{
	internal sealed class AsyncValue<T>
		: INotifyPropertyChanged
	{
		public AsyncValue (Task<T> task, T defaultValue = default(T), TaskScheduler scheduler = null)
		{
			if (task == null)
				throw new ArgumentNullException (nameof(task));

			this.task = task;
			this.defaultValue = defaultValue;

			if (scheduler == null) {
				scheduler = TaskScheduler.Current;
				if (SynchronizationContext.Current != null)
					scheduler = TaskScheduler.FromCurrentSynchronizationContext ();
			}

			this.task.ContinueWith (t => {
				IsRunning = false;
			}, scheduler);

			this.task.ContinueWith (t => {
				OnPropertyChanged (nameof(Value));
			}, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, scheduler);
		}

		public event PropertyChangedEventHandler PropertyChanged;

		public bool IsRunning
		{
			get { return this.isRunning; }
			set
			{
				if (this.isRunning == value)
					return;

				this.isRunning = value;
				OnPropertyChanged();
			}
		}

		public Task<T> Task => this.task;

		public T Value => (this.task.Status == TaskStatus.RanToCompletion) ? this.task.Result : this.defaultValue;

		private bool isRunning = true;
		private readonly Task<T> task;
		private readonly T defaultValue;

		private void OnPropertyChanged ([CallerMemberName] string propertyName = null)
		{
			PropertyChanged?.Invoke (this, new PropertyChangedEventArgs (propertyName));
		}
	}
}