Given an IObservable<Offer>
of offers
from merchants to buy or sell some type of item at a fixed price, we can match pairs of buyers and sellers as follows:
var sellers = offers.Where(offer => offer.IsSell).Select(offer => offer.Merchant);
var buyers = offers.Where(offer => offer.IsBuy).Select(offer => offer.Merchant);
var trades = Observable.Zip(sellers, buyers, (seller, buyer) => new Trade(seller, buyer));
The problem with this is that each subscription to trades
will subscribe to offers
twice. We can make sellers
and buyers
share a single subscription to offers
by using Publish
:
var trades = offers.Publish(_offers =>
{
var sellers = _offers.Where(offer => offer.IsSell).Select(offer => offer.User);
var buyers = _offers.Where(offer => offer.IsBuy).Select(offer => offer.User);
return Observable.Zip(sellers, buyers, (seller, buyer) => new Trade(seller, buyer));
});