共享单个订阅(发布)

鉴于来自商家的 IObservable<Offer> offers 以固定价格购买或出售某种类型的商品,我们可以按照以下方式匹配成对的买家和卖家:

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));

这个问题是每次订阅 trades 都会订阅 offers 两次。我们可以使用 Publishsellersbuyers 共享一个 offers 订阅:

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));
});