summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/StreamImageSource.cs
blob: 069267492141ccb9d0a0d1dea763ee6a89b41b23 (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
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Xamarin.Forms
{
	public class StreamImageSource : ImageSource, IStreamImageSource
	{
		public static readonly BindableProperty StreamProperty = BindableProperty.Create("Stream", typeof(Func<CancellationToken, Task<Stream>>), typeof(StreamImageSource),
			default(Func<CancellationToken, Task<Stream>>));

		public virtual Func<CancellationToken, Task<Stream>> Stream
		{
			get { return (Func<CancellationToken, Task<Stream>>)GetValue(StreamProperty); }
			set { SetValue(StreamProperty, value); }
		}

		protected override void OnPropertyChanged(string propertyName)
		{
			if (propertyName == StreamProperty.PropertyName)
				OnSourceChanged();
			base.OnPropertyChanged(propertyName);
		} 

		async Task<Stream> IStreamImageSource.GetStreamAsync(CancellationToken userToken)
		{
			if (Stream == null)
				return null;

			OnLoadingStarted();
			userToken.Register(CancellationTokenSource.Cancel);
			Stream stream = null;
			try
			{
				stream = await Stream(CancellationTokenSource.Token);
				OnLoadingCompleted(false);
			}
			catch (OperationCanceledException)
			{
				OnLoadingCompleted(true);
				throw;
			}
			return stream;
		}
	}
}