[英]Exception 'Sequence contains no elements' upon awaiting observable
I am using the System.Reactive.Linq
extension methods to convert an observable to a result in an async method. 我正在使用
System.Reactive.Linq
扩展方法将可观察对象转换为异步方法中的结果。 The code runs correctly when I have an object reference; 当我有一个对象引用时,代码可以正确运行; however, when I pass null into the
OnNext
method, the resulting awaiter throws 但是,当我将null传递给
OnNext
方法时,结果等待者抛出
System.InvalidOperationException
HResult=0x80131509
Message=Sequence contains no elements.
Source=System.Reactive
StackTrace:
at System.Reactive.Subjects.AsyncSubject`1.GetResult() in D:\a\1\s\Rx.NET\Source\src\System.Reactive\Subjects\AsyncSubject.cs:line 441
at <namespace>.DataServiceTests.<GetWithInvalidIdShouldReturnNull>d__5.MoveNext() in <local test code>
I am expecting the awaiter to get a null value. 我期望侍者得到一个空值。 My test is as follows:
我的测试如下:
[Fact]
public async void GetWithInvalidIdShouldReturnNull()
{
var testId = shortid.ShortId.Generate();
var result = await myTestOjbect.GetById(testId);
Assert.Null(result);
}
And the GetById
method is: 而
GetById
方法是:
public IObservable<object> GetById(string id)
{
return Observable.Create((IObserver<object> observer) => {
var item = this._repository.Get(id); // This returns null when id is not found in collection
observer.OnNext(item);
observer.OnCompleted();
return Disposable.Empty;
});
}
Works fine for me, though I did it in Linqpad. 尽管我在Linqpad中做到了,但对我来说效果很好。 Here's my code:
这是我的代码:
async Task Main()
{
var result = await GetById("");
if(result == null)
Console.WriteLine("OK!");
else
throw new Exception("Expected Null!");
}
public IObservable<object> GetById(string id)
{
var o = Observable.Create<object>(obs =>
{
obs.OnNext(null);
obs.OnCompleted();
return Disposable.Empty;
});
return o;
}
Here's where your error is being thrown: https://github.com/dotnet/reactive/blob/master/Rx.NET/Source/src/System.Reactive/Subjects/AsyncSubject.cs#L441 这是引发错误的地方: https : //github.com/dotnet/reactive/blob/master/Rx.NET/Source/src/System.Reactive/Subjects/AsyncSubject.cs#L441
Looks like your subject doesn't have any observers, or the observer(s) are already disposed. 看起来您的主题没有任何观察者,或者观察者已经被处置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.