Observable.FromAsyncPattern可用于从BeginX EndX样式的异步方法中创建一个observable。
也许我误解了一些东西,但是有一个类似的功能来从新的异步样式方法创建一个observable - 即.. Stream.ReadAsync?
答案 0 :(得分:6)
您可以使用ToObservable从IObservable<T>
创建Task<T>
:
using System.Reactive.Threading.Tasks;
Stream s = ...;
IObservable<int> o = s.ReadAsync(buffer, offset, count).ToObservable();
答案 1 :(得分:2)
请注意Lee的回答是正确的,但最终我最终做的是使用Observable.Create继续从流中读取,见下文 -
public static IConnectableObservable<Command> GetReadObservable(this CommandReader reader)
{
return Observable.Create<Command>(async (subject, token) =>
{
try
{
while (true)
{
if (token.IsCancellationRequested)
{
subject.OnCompleted();
return;
}
Command cmd = await reader.ReadCommandAsync();
subject.OnNext(cmd);
}
}
catch (Exception ex)
{
try
{
subject.OnError(ex);
}
catch (Exception)
{
Debug.WriteLine("An exception was thrown while trying to call OnError on the observable subject -- means you're not catching exceptions everywhere");
throw;
}
}
}).Publish();
}