Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8476417
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T18:10:24+00:00 2026-06-10T18:10:24+00:00

I want to run through an IObservable<T> looking for an element that matches a

  • 0

I want to run through an IObservable<T> looking for an element that matches a predicate, and if not found, return the last element of the IObservable<T>. I don’t want to have to store the entire contents of the IObservable<T>, and I don’t want to loop through the IObservable twice, so I’ve set up an extension method

public static class ObservableExtensions
{
    public static IObservable<T> FirstOrLastAsync<T>(this IObservable<T> source, Func<T, bool> pred)
    {
        return Observable.Create<T>(o =>
        {
            var hot = source.Publish();
            var store = new AsyncSubject<T>();
            var d1 = hot.Subscribe(store);
            var d2 = hot.FirstAsync(x => pred(x)).Amb(store).Subscribe(o);
            var d3 = hot.Connect();
            return new CompositeDisposable(d1, d2, d3);
        });
    }

    public static T FirstOrLast<T>(this IObservable<T> source, Func<T, bool> pred)
    {
        return source.FirstOrLastAsync(pred).Wait();
    }
}

The Async method creates a hot observable from a potentially cold one passed in. It subscribes an AsyncSubject<T> to remember the last element, and an IObservable<T> that looks for the element. It then takes the first element from either of those IObservable<T>s, which ever returns a value first via .Amb (AsyncSubject<T> doesn’t return a value until it gets an .OnCompleted message).

My questions are the following:

  • Can this be written better or more concisely using different Observable methods?
  • Do all of those disposables need to be included in the CompositeDisposable?
  • When the hot observable is completed without finding a matching element, is there a race condition between FirstAsync throwing an exception, and the AsyncSubject propagating its value?
  • If so, do I need to change the line to:

var d2 = hot.Where(x => pred(x)).Take(1).Amb(store).Subscribe(o);

I’m pretty new to RX, and this is my first extension on IObservable.

EDIT

I ended up going with

public static class ObservableExtensions
{
    public static IObservable<T> FirstOrLastAsync<T>(this IObservable<T> source, Func<T, bool> pred)
    {
        var hot = source.Publish().RefCount();
        return hot.TakeLast(1).Amb(hot.Where(pred).Take(1).Concat(Observable.Never<T>()));
    }

    public static T FirstOrLast<T>(this IObservable<T> source, Func<T, bool> pred)
    {
        return source.FirstOrLastAsync(pred).First();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T18:10:26+00:00Added an answer on June 10, 2026 at 6:10 pm

    You could Amb the two cases you want together.
    If your source observable is cold, you can do a Publish|Refcount.

        public static IObservable<T> FirstOrLast<T>(this IObservable<T> source, Func<T, bool> predicate)
        {
            return source.TakeLast(1).Amb(source.Where(predicate).Take(1));
        }
    

    Test:

            var source = Observable.Interval(TimeSpan.FromSeconds(0.1))
                                   .Take(10)
                                   .Publish()
                                   .RefCount();
    
            FirstOrLast(source, i => i == 5).Subscribe(Console.WriteLine); //5
            FirstOrLast(source, i => i == 11).Subscribe(Console.WriteLine); //9
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Perl script which I want to run every 4 hours through
I have a sql script file and i want to run that i can
I have a servlet and I want to run .java code through scriptlet. I
I have an array of values that I would like to run through htmlspecialchars
I have a java script code that works fine when run through a browser,
I have a small app that uses cocos2d to run through four levels of
I want to run weka through the command line. I type in this command:
I want to run this as a batch rather than through the command line:
Basiclly, I want to capture audio/video. Run it through a mp4 muxer and save
Why this code don't work,when i want run this code vwd 2008 express show

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.