[英]Observable for awaitable method C#
Observable.FromAsyncPattern can be used to make an observable from BeginX EndX style async methods. Observable.FromAsyncPattern可用于从BeginX EndX样式的异步方法中创建一个observable。
Maybe I'm misunderstanding things, but is there a similar function to create an observable from the new async style methods - ie.. Stream.ReadAsync? 也许我误解了一些事情,但是有一个类似的功能来从新的异步样式方法创建一个observable - 即.. Stream.ReadAsync?
You can create an IObservable<T>
from a Task<T>
using ToObservable : 您可以使用ToObservable从
Task<T>
创建IObservable<T>
:
using System.Reactive.Threading.Tasks;
Stream s = ...;
IObservable<int> o = s.ReadAsync(buffer, offset, count).ToObservable();
Note that Lee's answer is correct, but ultimately what I ended up doing was using Observable.Create to continually read from a stream, see below -- 请注意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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.