簡體   English   中英

等待觀察到的異常“序列不包含任何元素”

[英]Exception 'Sequence contains no elements' upon awaiting observable

我正在使用System.Reactive.Linq擴展方法將可觀察對象轉換為異步方法中的結果。 當我有一個對象引用時,代碼可以正確運行; 但是,當我將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>

我期望侍者得到一個空值。 我的測試如下:

[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;
}

這是引發錯誤的地方: https : //github.com/dotnet/reactive/blob/master/Rx.NET/Source/src/System.Reactive/Subjects/AsyncSubject.cs#L441

看起來您的主題沒有任何觀察者,或者觀察者已經被處置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM