我正在使用System.Reactive.Linq
扩展方法将observable转换为异步方法中的结果。当我有一个对象引用时,代码正确运行;然而,当我将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>
我期待awaiter得到一个空值。我的测试如下:
[Fact]
public async void GetWithInvalidIdShouldReturnNull()
{
var testId = shortid.ShortId.Generate();
var result = await myTestOjbect.GetById(testId);
Assert.Null(result);
}
而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;
});
}
虽然我在Linqpad中做到了,但对我来说工作正常。这是我的代码:
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;
}
看起来您的主题没有任何观察者,或者观察者已经处置掉了。