Ronnie Overby
Ronnie Overby

Reputation: 46470

Observable that wraps FromEventPattern while caching the most recent event for new subscribers

I have created an observable by using Observable.FromEventPattern. Let's call it fromEvents.

I want to create another observable that wraps fromEvents. We'll call this 2nd observable wrapper.

When wrapper is subscribed to it should:

  1. Publish the most recent item from fromEvents if any.
  2. Publish the rest of items coming from fromEvents

Obviously wrapper will need to maintain a subscription to fromEvents so that it always has access to the most recent event.

I have tried various combinations of Replay, Publish, PublishLast, Observable.Defer and I'm never quite getting the results I'm looking for.

I'm certain Rx has operators that will meet my needs, I'm just unsure of exactly how to put everything together, being the newb that I am.

Upvotes: 0

Views: 398

Answers (2)

Ronnie Overby
Ronnie Overby

Reputation: 46470

I think I've been able to get what I want by doing this:

Events = Observable.FromEventPattern(...).Replay(1).RefCount();

// contrived example
// in my real app the subscription lives for a specific duration
// and Events is exposed as a readonly property
using(Events.Subscribe())
{
     // get most recent or wait for first
    var e = Events.FirstAsync().Wait();
}

Upvotes: 1

Brandon
Brandon

Reputation: 39182

Example using the Publish overload that uses a BehaviorSubject behind the scenes to keep track of the most recent event.

var fromEvents = Observable.FromEventPattern(...);
var published = fromEvents.Publish(null);
// subscribe to this one
var wrapper = published.Where(e => e != null);
// start collecting values
var subscription = published.Connect();

wrapper.Subscribe(...);

Upvotes: 0

Related Questions