简体   繁体   中英

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. The code runs correctly when I have an object reference; however, when I pass null into the OnNext method, the resulting awaiter throws

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:

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. 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

Looks like your subject doesn't have any observers, or the observer(s) are already disposed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM