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;
    });
}
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.
 Timothy Jannace
 Timothy JannaceWorks 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;
}
User contributions licensed under CC BY-SA 3.0