AsyncInfoToObservableBridge<TResult, TProgress>
using System.Reactive.Subjects;
using System.Runtime.CompilerServices;
using Windows.Foundation;
namespace System.Reactive.Windows.Foundation
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(new byte[] {
0,
1
})]
internal class AsyncInfoToObservableBridge<[System.Runtime.CompilerServices.Nullable(2)] TResult, [System.Runtime.CompilerServices.Nullable(2)] TProgress> : ObservableBase<TResult>
{
private readonly Action<IAsyncInfo, Action<IAsyncInfo, AsyncStatus>> _onCompleted;
private readonly Func<IAsyncInfo, TResult> _getResult;
private readonly AsyncSubject<TResult> _subject;
public AsyncInfoToObservableBridge(IAsyncInfo info, Action<IAsyncInfo, Action<IAsyncInfo, AsyncStatus>> onCompleted, Func<IAsyncInfo, TResult> getResult, [System.Runtime.CompilerServices.Nullable(new byte[] {
2,
1,
1,
1,
1
})] Action<IAsyncInfo, Action<IAsyncInfo, TProgress>> onProgress, [System.Runtime.CompilerServices.Nullable(new byte[] {
2,
1
})] IProgress<TProgress> progress, bool multiValue)
{
_onCompleted = onCompleted;
_getResult = getResult;
_subject = new AsyncSubject<TResult>();
onProgress?.Invoke(info, delegate(IAsyncInfo iai, TProgress p) {
if (multiValue && getResult != null)
_subject.OnNext(getResult(iai));
progress?.Report(p);
});
Done(info, info.get_Status(), true);
}
private void Done(IAsyncInfo info, AsyncStatus status, bool initial)
{
Exception ex = null;
TResult value = default(TResult);
switch (status - 1) {
case 2:
ex = info.get_ErrorCode();
if (ex == null)
throw new InvalidOperationException("The asynchronous operation failed with a null error code.");
break;
case 1:
ex = new OperationCanceledException();
break;
case 0:
if (_getResult != null)
value = _getResult(info);
break;
default:
if (!initial)
throw new InvalidOperationException("The asynchronous operation completed unexpectedly.");
_onCompleted(info, delegate(IAsyncInfo iai, AsyncStatus s) {
Done(iai, s, false);
});
return;
}
info.Close();
if (ex != null)
_subject.OnError(ex);
else {
if (_getResult != null)
_subject.OnNext(value);
_subject.OnCompleted();
}
}
protected override IDisposable SubscribeCore(IObserver<TResult> observer)
{
return _subject.Subscribe(observer);
}
}
}