在等待可观察时,异常'序列不包含任何元素'

问题描述 投票:-1回答:2

我正在使用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;
    });
}
c# .net-core system.reactive
2个回答
-1
投票

虽然我在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;
}

-1
投票

这是你的错误抛出的地方:https://github.com/dotnet/reactive/blob/master/Rx.NET/Source/src/System.Reactive/Subjects/AsyncSubject.cs#L441

看起来您的主题没有任何观察者,或者观察者已经处置掉了。

© www.soinside.com 2019 - 2024. All rights reserved.