dotnet/reactive · error · InvalidOperationException

Strings_Linq.NO_MATCHING_ELEMENTS

Error message

Strings_Linq.NO_MATCHING_ELEMENTS

What it means

LastAsync with a predicate throws InvalidOperationException with Strings_Linq.NO_MATCHING_ELEMENTS when the source completes and no emitted element matched the predicate (_seenValue stays false). Forwarded via OnError.

Solutions

  1. Use LastOrDefaultAsync(predicate) to get default(T) instead of an error
  2. Catch InvalidOperationException in OnError and fall back
  3. Verify the predicate against the emitted data

Example fix

// before
source.LastAsync(x => x.IsFinal).Subscribe(...);
// after
source.LastOrDefaultAsync(x => x.IsFinal).Subscribe(x => ...);
Defensive patterns

Strategy: try-catch

Try / catch

source.LastAsync(pred).Subscribe(
    x => Console.WriteLine(x),
    ex => { if (ex is InvalidOperationException) Console.WriteLine(default); else throw ex; });

Prevention

When it happens

Trigger: Subscribing to source.LastAsync(x => predicate(x)) where no element satisfies the predicate before completion.

Common situations: Finding the last matching log entry in a stream where the condition never occurs; filtering by a state change that never happened.

Understand the failure class

Background: EmptyResultError / "no results found": when an API or scraper succeeds but returns zero rows — this error's family across 9 libraries.

Related errors


AI-assisted analysis of dotnet/reactive@94b5d5ab91 (2026-09-15). Data as JSON: /api/errors/7ebf59b3197c07a5. Report an issue: GitHub.

Appendix: source

Thrown at Rx.NET/Source/src/System.Reactive/Linq/Observable/LastAsync.cs:130

                    {
                        _value = value;
                        _seenValue = true;
                    }
                }

                public override void OnError(Exception error)
                {
                    _value = default;
                    ForwardOnError(error);
                }

                public override void OnCompleted()
                {
                    if (!_seenValue)
                    {
                        try
                        {
                            throw new InvalidOperationException(Strings_Linq.NO_MATCHING_ELEMENTS);
                        }
                        catch (Exception e)
                        {
                            ForwardOnError(e);
                        }
                    }
                    else
                    {
                        var value = _value!;
                        _value = default;
                        ForwardOnNext(value);
                        ForwardOnCompleted();
                    }
                }
            }
        }
    }
}

View on GitHub (pinned to 94b5d5ab91)